acme.sh 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176
  1. #!/usr/bin/env sh
  2. VER=2.6.0
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  10. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  11. DEFAULT_USER_AGENT="$PROJECT_ENTRY client v$VER : $PROJECT"
  12. DEFAULT_ACCOUNT_EMAIL=""
  13. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  14. VTYPE_HTTP="http-01"
  15. VTYPE_DNS="dns-01"
  16. VTYPE_TLS="tls-sni-01"
  17. VTYPE_TLS2="tls-sni-02"
  18. LOCAL_ANY_ADDRESS="0.0.0.0"
  19. MAX_RENEW=60
  20. DEFAULT_DNS_SLEEP=120
  21. NO_VALUE="no"
  22. W_TLS="tls"
  23. STATE_VERIFIED="verified_ok"
  24. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  25. END_CSR="-----END CERTIFICATE REQUEST-----"
  26. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  27. END_CERT="-----END CERTIFICATE-----"
  28. RENEW_SKIP=2
  29. ECC_SEP="_"
  30. ECC_SUFFIX="${ECC_SEP}ecc"
  31. LOG_LEVEL_1=1
  32. LOG_LEVEL_2=2
  33. LOG_LEVEL_3=3
  34. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  35. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  36. __INTERACTIVE=""
  37. if [ -t 1 ] ; then
  38. __INTERACTIVE="1"
  39. fi
  40. __green() {
  41. if [ "$__INTERACTIVE" ] ; then
  42. printf '\033[1;31;32m'
  43. fi
  44. printf -- "$1"
  45. if [ "$__INTERACTIVE" ] ; then
  46. printf '\033[0m'
  47. fi
  48. }
  49. __red() {
  50. if [ "$__INTERACTIVE" ] ; then
  51. printf '\033[1;31;40m'
  52. fi
  53. printf -- "$1"
  54. if [ "$__INTERACTIVE" ] ; then
  55. printf '\033[0m'
  56. fi
  57. }
  58. _printargs() {
  59. if [ -z "$2" ] ; then
  60. printf -- "[$(date)] $1"
  61. else
  62. printf -- "[$(date)] $1='$2'"
  63. fi
  64. printf "\n"
  65. }
  66. _log() {
  67. [ -z "$LOG_FILE" ] && return
  68. _printargs "$@" >> "$LOG_FILE"
  69. }
  70. _info() {
  71. _log "$@"
  72. _printargs "$@"
  73. }
  74. _err() {
  75. _log "$@"
  76. printf -- "[$(date)] " >&2
  77. if [ -z "$2" ] ; then
  78. __red "$1" >&2
  79. else
  80. __red "$1='$2'" >&2
  81. fi
  82. printf "\n" >&2
  83. return 1
  84. }
  85. _usage() {
  86. __red "$@" >&2
  87. printf "\n" >&2
  88. }
  89. _debug() {
  90. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ] ; then
  91. _log "$@"
  92. fi
  93. if [ -z "$DEBUG" ] ; then
  94. return
  95. fi
  96. _printargs "$@" >&2
  97. }
  98. _debug2() {
  99. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ] ; then
  100. _log "$@"
  101. fi
  102. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  103. _debug "$@"
  104. fi
  105. }
  106. _debug3() {
  107. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ] ; then
  108. _log "$@"
  109. fi
  110. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ] ; then
  111. _debug "$@"
  112. fi
  113. }
  114. _startswith(){
  115. _str="$1"
  116. _sub="$2"
  117. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  118. }
  119. _endswith(){
  120. _str="$1"
  121. _sub="$2"
  122. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  123. }
  124. _contains(){
  125. _str="$1"
  126. _sub="$2"
  127. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  128. }
  129. _hasfield() {
  130. _str="$1"
  131. _field="$2"
  132. _sep="$3"
  133. if [ -z "$_field" ] ; then
  134. _usage "Usage: str field [sep]"
  135. return 1
  136. fi
  137. if [ -z "$_sep" ] ; then
  138. _sep=","
  139. fi
  140. for f in $(echo "$_str" | tr ',' ' ') ; do
  141. if [ "$f" = "$_field" ] ; then
  142. _debug2 "'$_str' contains '$_field'"
  143. return 0 #contains ok
  144. fi
  145. done
  146. _debug2 "'$_str' does not contain '$_field'"
  147. return 1 #not contains
  148. }
  149. _getfield(){
  150. _str="$1"
  151. _findex="$2"
  152. _sep="$3"
  153. if [ -z "$_findex" ] ; then
  154. _usage "Usage: str field [sep]"
  155. return 1
  156. fi
  157. if [ -z "$_sep" ] ; then
  158. _sep=","
  159. fi
  160. _ffi=$_findex
  161. while [ "$_ffi" -gt "0" ]
  162. do
  163. _fv="$(echo "$_str" | cut -d $_sep -f $_ffi)"
  164. if [ "$_fv" ] ; then
  165. printf -- "%s" "$_fv"
  166. return 0
  167. fi
  168. _ffi="$(_math $_ffi - 1)"
  169. done
  170. printf -- "%s" "$_str"
  171. }
  172. _exists(){
  173. cmd="$1"
  174. if [ -z "$cmd" ] ; then
  175. _usage "Usage: _exists cmd"
  176. return 1
  177. fi
  178. if type command >/dev/null 2>&1 ; then
  179. command -v "$cmd" >/dev/null 2>&1
  180. else
  181. type "$cmd" >/dev/null 2>&1
  182. fi
  183. ret="$?"
  184. _debug3 "$cmd exists=$ret"
  185. return $ret
  186. }
  187. #a + b
  188. _math(){
  189. expr "$@"
  190. }
  191. _h_char_2_dec() {
  192. _ch=$1
  193. case "${_ch}" in
  194. a|A)
  195. printf "10"
  196. ;;
  197. b|B)
  198. printf "11"
  199. ;;
  200. c|C)
  201. printf "12"
  202. ;;
  203. d|D)
  204. printf "13"
  205. ;;
  206. e|E)
  207. printf "14"
  208. ;;
  209. f|F)
  210. printf "15"
  211. ;;
  212. *)
  213. printf "%s" "$_ch"
  214. ;;
  215. esac
  216. }
  217. _URGLY_PRINTF=""
  218. if [ "$(printf '\x41')" != 'A' ] ; then
  219. _URGLY_PRINTF=1
  220. fi
  221. _h2b() {
  222. hex=$(cat)
  223. i=1
  224. j=2
  225. if _exists let ; then
  226. uselet="1"
  227. fi
  228. _debug3 uselet "$uselet"
  229. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  230. while true ; do
  231. if [ -z "$_URGLY_PRINTF" ] ; then
  232. h="$(printf $hex | cut -c $i-$j)"
  233. if [ -z "$h" ] ; then
  234. break;
  235. fi
  236. printf "\x$h"
  237. else
  238. ic="$(printf $hex | cut -c $i)"
  239. jc="$(printf $hex | cut -c $j)"
  240. if [ -z "$ic$jc" ] ; then
  241. break;
  242. fi
  243. ic="$(_h_char_2_dec "$ic")"
  244. jc="$(_h_char_2_dec "$jc")"
  245. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  246. fi
  247. if [ "$uselet" ] ; then
  248. let "i+=2" >/dev/null
  249. let "j+=2" >/dev/null
  250. else
  251. i="$(_math $i + 2)"
  252. j="$(_math $j + 2)"
  253. fi
  254. done
  255. }
  256. #options file
  257. _sed_i() {
  258. options="$1"
  259. filename="$2"
  260. if [ -z "$filename" ] ; then
  261. _usage "Usage:_sed_i options filename"
  262. return 1
  263. fi
  264. _debug2 options "$options"
  265. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  266. _debug "Using sed -i"
  267. sed -i "$options" "$filename"
  268. else
  269. _debug "No -i support in sed"
  270. text="$(cat "$filename")"
  271. echo "$text" | sed "$options" > "$filename"
  272. fi
  273. }
  274. _egrep_o() {
  275. if _contains "$(egrep -o 2>&1)" "egrep: illegal option -- o" ; then
  276. sed -n 's/.*\('"$1"'\).*/\1/p'
  277. else
  278. egrep -o "$1"
  279. fi
  280. }
  281. #Usage: file startline endline
  282. _getfile() {
  283. filename="$1"
  284. startline="$2"
  285. endline="$3"
  286. if [ -z "$endline" ] ; then
  287. _usage "Usage: file startline endline"
  288. return 1
  289. fi
  290. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  291. if [ -z "$i" ] ; then
  292. _err "Can not find start line: $startline"
  293. return 1
  294. fi
  295. i="$(_math "$i" + 1)"
  296. _debug i "$i"
  297. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  298. if [ -z "$j" ] ; then
  299. _err "Can not find end line: $endline"
  300. return 1
  301. fi
  302. j="$(_math "$j" - 1)"
  303. _debug j "$j"
  304. sed -n "$i,${j}p" "$filename"
  305. }
  306. #Usage: multiline
  307. _base64() {
  308. if [ "$1" ] ; then
  309. openssl base64 -e
  310. else
  311. openssl base64 -e | tr -d '\r\n'
  312. fi
  313. }
  314. #Usage: multiline
  315. _dbase64() {
  316. if [ "$1" ] ; then
  317. openssl base64 -d -A
  318. else
  319. openssl base64 -d
  320. fi
  321. }
  322. #Usage: hashalg [outputhex]
  323. #Output Base64-encoded digest
  324. _digest() {
  325. alg="$1"
  326. if [ -z "$alg" ] ; then
  327. _usage "Usage: _digest hashalg"
  328. return 1
  329. fi
  330. outputhex="$2"
  331. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  332. if [ "$outputhex" ] ; then
  333. openssl dgst -$alg -hex | cut -d = -f 2 | tr -d ' '
  334. else
  335. openssl dgst -$alg -binary | _base64
  336. fi
  337. else
  338. _err "$alg is not supported yet"
  339. return 1
  340. fi
  341. }
  342. #Usage: keyfile hashalg
  343. #Output: Base64-encoded signature value
  344. _sign() {
  345. keyfile="$1"
  346. alg="$2"
  347. if [ -z "$alg" ] ; then
  348. _usage "Usage: _sign keyfile hashalg"
  349. return 1
  350. fi
  351. if [ "$alg" = "sha256" ] ; then
  352. openssl dgst -sha256 -sign "$keyfile" | _base64
  353. else
  354. _err "$alg is not supported yet"
  355. return 1
  356. fi
  357. }
  358. #keylength
  359. _isEccKey() {
  360. _length="$1"
  361. if [ -z "$_length" ] ;then
  362. return 1
  363. fi
  364. [ "$_length" != "1024" ] \
  365. && [ "$_length" != "2048" ] \
  366. && [ "$_length" != "3072" ] \
  367. && [ "$_length" != "4096" ] \
  368. && [ "$_length" != "8192" ]
  369. }
  370. # _createkey 2048|ec-256 file
  371. _createkey() {
  372. length="$1"
  373. f="$2"
  374. eccname="$length"
  375. if _startswith "$length" "ec-" ; then
  376. length=$(printf $length | cut -d '-' -f 2-100)
  377. if [ "$length" = "256" ] ; then
  378. eccname="prime256v1"
  379. fi
  380. if [ "$length" = "384" ] ; then
  381. eccname="secp384r1"
  382. fi
  383. if [ "$length" = "521" ] ; then
  384. eccname="secp521r1"
  385. fi
  386. fi
  387. if [ -z "$length" ] ; then
  388. length=2048
  389. fi
  390. _debug "Use length $length"
  391. if _isEccKey "$length" ; then
  392. _debug "Using ec name: $eccname"
  393. openssl ecparam -name $eccname -genkey 2>/dev/null > "$f"
  394. else
  395. _debug "Using RSA: $length"
  396. openssl genrsa $length 2>/dev/null > "$f"
  397. fi
  398. if [ "$?" != "0" ] ; then
  399. _err "Create key error."
  400. return 1
  401. fi
  402. }
  403. #_createcsr cn san_list keyfile csrfile conf
  404. _createcsr() {
  405. _debug _createcsr
  406. domain="$1"
  407. domainlist="$2"
  408. csrkey="$3"
  409. csr="$4"
  410. csrconf="$5"
  411. _debug2 domain "$domain"
  412. _debug2 domainlist "$domainlist"
  413. _debug2 csrkey "$csrkey"
  414. _debug2 csr "$csr"
  415. _debug2 csrconf "$csrconf"
  416. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" > "$csrconf"
  417. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  418. #single domain
  419. _info "Single domain" "$domain"
  420. else
  421. if _contains "$domainlist" "," ; then
  422. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  423. else
  424. alt="DNS:$domainlist"
  425. fi
  426. #multi
  427. _info "Multi domain" "$alt"
  428. printf -- "\nsubjectAltName=$alt" >> "$csrconf"
  429. fi
  430. if [ "$Le_OCSP_Stable" ] ; then
  431. _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
  432. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "$csrconf"
  433. fi
  434. openssl req -new -sha256 -key "$csrkey" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  435. }
  436. #_signcsr key csr conf cert
  437. _signcsr() {
  438. key="$1"
  439. csr="$2"
  440. conf="$3"
  441. cert="$4"
  442. _debug "_signcsr"
  443. _msg="$(openssl x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  444. _ret="$?"
  445. _debug "$_msg"
  446. return $_ret
  447. }
  448. #_csrfile
  449. _readSubjectFromCSR() {
  450. _csrfile="$1"
  451. if [ -z "$_csrfile" ] ; then
  452. _usage "_readSubjectFromCSR mycsr.csr"
  453. return 1
  454. fi
  455. openssl req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  456. }
  457. #_csrfile
  458. #echo comma separated domain list
  459. _readSubjectAltNamesFromCSR() {
  460. _csrfile="$1"
  461. if [ -z "$_csrfile" ] ; then
  462. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  463. return 1
  464. fi
  465. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  466. _debug _csrsubj "$_csrsubj"
  467. _dnsAltnames="$(openssl req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  468. _debug _dnsAltnames "$_dnsAltnames"
  469. if _contains "$_dnsAltnames," "DNS:$_csrsubj," ; then
  470. _debug "AltNames contains subject"
  471. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  472. else
  473. _debug "AltNames doesn't contain subject"
  474. fi
  475. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  476. }
  477. #_csrfile
  478. _readKeyLengthFromCSR() {
  479. _csrfile="$1"
  480. if [ -z "$_csrfile" ] ; then
  481. _usage "_readKeyLengthFromCSR mycsr.csr"
  482. return 1
  483. fi
  484. _outcsr="$(openssl req -noout -text -in "$_csrfile")"
  485. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey" ; then
  486. _debug "ECC CSR"
  487. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  488. else
  489. _debug "RSA CSR"
  490. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  491. fi
  492. }
  493. _ss() {
  494. _port="$1"
  495. if _exists "ss" ; then
  496. _debug "Using: ss"
  497. ss -ntpl | grep ":$_port "
  498. return 0
  499. fi
  500. if _exists "netstat" ; then
  501. _debug "Using: netstat"
  502. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  503. #for windows version netstat tool
  504. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  505. else
  506. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  507. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  508. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null ; then
  509. #for solaris
  510. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  511. else
  512. netstat -ntpl | grep ":$_port "
  513. fi
  514. fi
  515. return 0
  516. fi
  517. return 1
  518. }
  519. #domain [password] [isEcc]
  520. toPkcs() {
  521. domain="$1"
  522. pfxPassword="$2"
  523. if [ -z "$domain" ] ; then
  524. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  525. return 1
  526. fi
  527. _isEcc="$3"
  528. _initpath "$domain" "$_isEcc"
  529. if [ "$pfxPassword" ] ; then
  530. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  531. else
  532. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  533. fi
  534. if [ "$?" = "0" ] ; then
  535. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  536. fi
  537. }
  538. #[2048]
  539. createAccountKey() {
  540. _info "Creating account key"
  541. if [ -z "$1" ] ; then
  542. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  543. return
  544. fi
  545. length=$1
  546. if _isEccKey "$length" ; then
  547. length=2048
  548. fi
  549. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ] ; then
  550. _debug "Use default length 2048"
  551. length=2048
  552. fi
  553. _debug length "$length"
  554. _initpath
  555. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  556. _info "Account key exists, skip"
  557. return
  558. else
  559. #generate account key
  560. _createkey "$length" "$ACCOUNT_KEY_PATH"
  561. fi
  562. }
  563. #domain [length]
  564. createDomainKey() {
  565. _info "Creating domain key"
  566. if [ -z "$1" ] ; then
  567. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  568. return
  569. fi
  570. domain=$1
  571. length=$2
  572. _initpath $domain "$length"
  573. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  574. _createkey "$length" "$CERT_KEY_PATH"
  575. else
  576. if [ "$IS_RENEW" ] ; then
  577. _info "Domain key exists, skip"
  578. return 0
  579. else
  580. _err "Domain key exists, do you want to overwrite the key?"
  581. _err "Add '--force', and try again."
  582. return 1
  583. fi
  584. fi
  585. }
  586. # domain domainlist isEcc
  587. createCSR() {
  588. _info "Creating csr"
  589. if [ -z "$1" ] ; then
  590. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  591. return
  592. fi
  593. domain="$1"
  594. domainlist="$2"
  595. _isEcc="$3"
  596. _initpath "$domain" "$_isEcc"
  597. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  598. _info "CSR exists, skip"
  599. return
  600. fi
  601. if [ ! -f "$CERT_KEY_PATH" ] ; then
  602. _err "The key file is not found: $CERT_KEY_PATH"
  603. _err "Please create the key file first."
  604. return 1
  605. fi
  606. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  607. }
  608. _urlencode() {
  609. __n=$(cat)
  610. echo $__n | tr '/+' '_-' | tr -d '= '
  611. }
  612. _time2str() {
  613. #BSD
  614. if date -u -d@$1 2>/dev/null ; then
  615. return
  616. fi
  617. #Linux
  618. if date -u -r $1 2>/dev/null ; then
  619. return
  620. fi
  621. #Soaris
  622. if _exists adb ; then
  623. echo $(echo "0t${1}=Y" | adb)
  624. fi
  625. }
  626. _normalizeJson() {
  627. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  628. }
  629. _stat() {
  630. #Linux
  631. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  632. return
  633. fi
  634. #BSD
  635. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  636. return
  637. fi
  638. return 1; #error, 'stat' not found
  639. }
  640. #keyfile
  641. _calcjwk() {
  642. keyfile="$1"
  643. if [ -z "$keyfile" ] ; then
  644. _usage "Usage: _calcjwk keyfile"
  645. return 1
  646. fi
  647. EC_SIGN=""
  648. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  649. _debug "RSA key"
  650. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  651. if [ "${#pub_exp}" = "5" ] ; then
  652. pub_exp=0$pub_exp
  653. fi
  654. _debug3 pub_exp "$pub_exp"
  655. e=$(echo $pub_exp | _h2b | _base64)
  656. _debug3 e "$e"
  657. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  658. _debug3 modulus "$modulus"
  659. n="$(printf "%s" "$modulus"| _h2b | _base64 | _urlencode )"
  660. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  661. _debug3 jwk "$jwk"
  662. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  663. HEADERPLACE_PART1='{"nonce": "'
  664. HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  665. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  666. _debug "EC key"
  667. EC_SIGN="1"
  668. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  669. _debug3 crv "$crv"
  670. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  671. pubi=$(_math $pubi + 1)
  672. _debug3 pubi "$pubi"
  673. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  674. pubj=$(_math $pubj + 1)
  675. _debug3 pubj "$pubj"
  676. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  677. _debug3 pubtext "$pubtext"
  678. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  679. xlen=$(_math $xlen / 4)
  680. _debug3 xlen "$xlen"
  681. xend=$(_math "$xend" + 1)
  682. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  683. _debug3 x "$x"
  684. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  685. _debug3 x64 "$x64"
  686. xend=$(_math "$xend" + 1)
  687. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  688. _debug3 y "$y"
  689. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  690. _debug3 y64 "$y64"
  691. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  692. _debug3 jwk "$jwk"
  693. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  694. HEADERPLACE_PART1='{"nonce": "'
  695. HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  696. else
  697. _err "Only RSA or EC key is supported."
  698. return 1
  699. fi
  700. _debug3 HEADER "$HEADER"
  701. }
  702. _time() {
  703. date -u "+%s"
  704. }
  705. _mktemp() {
  706. if _exists mktemp ; then
  707. if mktemp 2>/dev/null ; then
  708. return
  709. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null ; then
  710. #for Mac osx
  711. return
  712. fi
  713. fi
  714. if [ -d "/tmp" ] ; then
  715. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  716. return 0
  717. fi
  718. _err "Can not create temp file."
  719. }
  720. _inithttp() {
  721. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER" ; then
  722. HTTP_HEADER="$(_mktemp)"
  723. _debug2 HTTP_HEADER "$HTTP_HEADER"
  724. fi
  725. if [ -z "$CURL" ] ; then
  726. CURL="curl -L --silent --dump-header $HTTP_HEADER "
  727. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  728. _CURL_DUMP="$(_mktemp)"
  729. CURL="$CURL --trace-ascii $_CURL_DUMP "
  730. fi
  731. if [ "$CA_BUNDLE" ] ; then
  732. CURL="$CURL --cacert $CA_BUNDLE "
  733. fi
  734. if [ "$HTTPS_INSECURE" ] ; then
  735. CURL="$CURL --insecure "
  736. fi
  737. fi
  738. if [ -z "$WGET" ] ; then
  739. WGET="wget -q"
  740. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  741. WGET="$WGET -d "
  742. fi
  743. if [ "$CA_BUNDLE" ] ; then
  744. WGET="$WGET --ca-certificate $CA_BUNDLE "
  745. fi
  746. if [ "$HTTPS_INSECURE" ] ; then
  747. WGET="$WGET --no-check-certificate "
  748. fi
  749. fi
  750. }
  751. # body url [needbase64] [POST|PUT]
  752. _post() {
  753. body="$1"
  754. url="$2"
  755. needbase64="$3"
  756. httpmethod="$4"
  757. if [ -z "$httpmethod" ] ; then
  758. httpmethod="POST"
  759. fi
  760. _debug $httpmethod
  761. _debug "url" "$url"
  762. _debug2 "body" "$body"
  763. _inithttp
  764. if _exists "curl" ; then
  765. _CURL="$CURL"
  766. _debug "_CURL" "$_CURL"
  767. if [ "$needbase64" ] ; then
  768. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  769. else
  770. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" )"
  771. fi
  772. _ret="$?"
  773. if [ "$_ret" != "0" ] ; then
  774. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  775. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  776. _err "Here is the curl dump log:"
  777. _err "$(cat "$_CURL_DUMP")"
  778. fi
  779. fi
  780. elif _exists "wget" ; then
  781. _debug "WGET" "$WGET"
  782. if [ "$needbase64" ] ; then
  783. if [ "$httpmethod"="POST" ] ; then
  784. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  785. else
  786. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  787. fi
  788. else
  789. if [ "$httpmethod"="POST" ] ; then
  790. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  791. else
  792. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  793. fi
  794. fi
  795. _ret="$?"
  796. if [ "$_ret" = "8" ] ; then
  797. _ret=0
  798. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  799. fi
  800. if [ "$_ret" != "0" ] ; then
  801. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  802. fi
  803. _sed_i "s/^ *//g" "$HTTP_HEADER"
  804. else
  805. _ret="$?"
  806. _err "Neither curl nor wget is found, can not do $httpmethod."
  807. fi
  808. _debug "_ret" "$_ret"
  809. printf "%s" "$response"
  810. return $_ret
  811. }
  812. # url getheader timeout
  813. _get() {
  814. _debug GET
  815. url="$1"
  816. onlyheader="$2"
  817. t="$3"
  818. _debug url $url
  819. _debug "timeout" "$t"
  820. _inithttp
  821. if _exists "curl" ; then
  822. _CURL="$CURL"
  823. if [ "$t" ] ; then
  824. _CURL="$_CURL --connect-timeout $t"
  825. fi
  826. _debug "_CURL" "$_CURL"
  827. if [ "$onlyheader" ] ; then
  828. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  829. else
  830. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  831. fi
  832. ret=$?
  833. if [ "$ret" != "0" ] ; then
  834. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  835. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  836. _err "Here is the curl dump log:"
  837. _err "$(cat "$_CURL_DUMP")"
  838. fi
  839. fi
  840. elif _exists "wget" ; then
  841. _WGET="$WGET"
  842. if [ "$t" ] ; then
  843. _WGET="$_WGET --timeout=$t"
  844. fi
  845. _debug "_WGET" "$_WGET"
  846. if [ "$onlyheader" ] ; then
  847. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  848. else
  849. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  850. fi
  851. ret=$?
  852. if [ "$_ret" = "8" ] ; then
  853. _ret=0
  854. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  855. fi
  856. if [ "$ret" != "0" ] ; then
  857. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  858. fi
  859. else
  860. ret=$?
  861. _err "Neither curl nor wget is found, can not do GET."
  862. fi
  863. _debug "ret" "$ret"
  864. return $ret
  865. }
  866. _head_n() {
  867. head -n $1
  868. }
  869. _tail_n() {
  870. if ! tail -n $1 2>/dev/null ; then
  871. #fix for solaris
  872. tail -$1
  873. fi
  874. }
  875. # url payload needbase64 keyfile
  876. _send_signed_request() {
  877. url=$1
  878. payload=$2
  879. needbase64=$3
  880. keyfile=$4
  881. if [ -z "$keyfile" ] ; then
  882. keyfile="$ACCOUNT_KEY_PATH"
  883. fi
  884. _debug url $url
  885. _debug payload "$payload"
  886. if ! _calcjwk "$keyfile" ; then
  887. return 1
  888. fi
  889. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  890. _debug3 payload64 $payload64
  891. nonceurl="$API/directory"
  892. _headers="$(_get $nonceurl "onlyheader")"
  893. if [ "$?" != "0" ] ; then
  894. _err "Can not connect to $nonceurl to get nonce."
  895. return 1
  896. fi
  897. _debug3 _headers "$_headers"
  898. nonce="$( echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  899. _debug3 nonce "$nonce"
  900. protected="$HEADERPLACE_PART1$nonce$HEADERPLACE_PART2"
  901. _debug3 protected "$protected"
  902. protected64="$(printf "$protected" | _base64 | _urlencode)"
  903. _debug3 protected64 "$protected64"
  904. sig=$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  905. _debug3 sig "$sig"
  906. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  907. _debug3 body "$body"
  908. response="$(_post "$body" $url "$needbase64")"
  909. if [ "$?" != "0" ] ; then
  910. _err "Can not post to $url"
  911. return 1
  912. fi
  913. _debug2 original "$response"
  914. response="$( echo "$response" | _normalizeJson )"
  915. responseHeaders="$(cat $HTTP_HEADER)"
  916. _debug2 responseHeaders "$responseHeaders"
  917. _debug2 response "$response"
  918. code="$(grep "^HTTP" $HTTP_HEADER | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n" )"
  919. _debug code $code
  920. }
  921. #setopt "file" "opt" "=" "value" [";"]
  922. _setopt() {
  923. __conf="$1"
  924. __opt="$2"
  925. __sep="$3"
  926. __val="$4"
  927. __end="$5"
  928. if [ -z "$__opt" ] ; then
  929. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  930. return
  931. fi
  932. if [ ! -f "$__conf" ] ; then
  933. touch "$__conf"
  934. fi
  935. if grep -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  936. _debug3 OK
  937. if _contains "$__val" "&" ; then
  938. __val="$(echo $__val | sed 's/&/\\&/g')"
  939. fi
  940. text="$(cat $__conf)"
  941. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  942. elif grep -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  943. if _contains "$__val" "&" ; then
  944. __val="$(echo $__val | sed 's/&/\\&/g')"
  945. fi
  946. text="$(cat $__conf)"
  947. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  948. else
  949. _debug3 APP
  950. echo "$__opt$__sep$__val$__end" >> "$__conf"
  951. fi
  952. _debug2 "$(grep -n "^$__opt$__sep" $__conf)"
  953. }
  954. #_savedomainconf key value
  955. #save to domain.conf
  956. _savedomainconf() {
  957. _sdkey="$1"
  958. _sdvalue="$2"
  959. if [ "$DOMAIN_CONF" ] ; then
  960. _setopt "$DOMAIN_CONF" "$_sdkey" "=" "\"$_sdvalue\""
  961. else
  962. _err "DOMAIN_CONF is empty, can not save $_sdkey=$_sdvalue"
  963. fi
  964. }
  965. #_cleardomainconf key
  966. _cleardomainconf() {
  967. _sdkey="$1"
  968. if [ "$DOMAIN_CONF" ] ; then
  969. _sed_i "s/^$_sdkey.*$//" "$DOMAIN_CONF"
  970. else
  971. _err "DOMAIN_CONF is empty, can not save $_sdkey=$value"
  972. fi
  973. }
  974. #_readdomainconf key
  975. _readdomainconf() {
  976. _sdkey="$1"
  977. if [ "$DOMAIN_CONF" ] ; then
  978. (
  979. eval $(grep "^$_sdkey *=" "$DOMAIN_CONF")
  980. eval "printf \"%s\" \"\$$_sdkey\""
  981. )
  982. else
  983. _err "DOMAIN_CONF is empty, can not read $_sdkey"
  984. fi
  985. }
  986. #_saveaccountconf key value
  987. _saveaccountconf() {
  988. _sckey="$1"
  989. _scvalue="$2"
  990. if [ "$ACCOUNT_CONF_PATH" ] ; then
  991. _setopt "$ACCOUNT_CONF_PATH" "$_sckey" "=" "\"$_scvalue\""
  992. else
  993. _err "ACCOUNT_CONF_PATH is empty, can not save $_sckey=$_scvalue"
  994. fi
  995. }
  996. #_clearaccountconf key
  997. _clearaccountconf() {
  998. _scvalue="$1"
  999. if [ "$ACCOUNT_CONF_PATH" ] ; then
  1000. _sed_i "s/^$_scvalue.*$//" "$ACCOUNT_CONF_PATH"
  1001. else
  1002. _err "ACCOUNT_CONF_PATH is empty, can not clear $_scvalue"
  1003. fi
  1004. }
  1005. # content localaddress
  1006. _startserver() {
  1007. content="$1"
  1008. ncaddr="$2"
  1009. _debug "ncaddr" "$ncaddr"
  1010. _debug "startserver: $$"
  1011. nchelp="$(nc -h 2>&1)"
  1012. _debug Le_HTTPPort "$Le_HTTPPort"
  1013. _debug Le_Listen_V4 "$Le_Listen_V4"
  1014. _debug Le_Listen_V6 "$Le_Listen_V6"
  1015. _NC="nc"
  1016. if [ "$Le_Listen_V4" ] ; then
  1017. _NC="$_NC -4"
  1018. elif [ "$Le_Listen_V6" ] ; then
  1019. _NC="$_NC -6"
  1020. fi
  1021. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  1022. _NC="$_NC -q 1 -l $ncaddr"
  1023. else
  1024. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  1025. _NC="$_NC -c -l $ncaddr"
  1026. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  1027. _NC="$_NC -N -l $ncaddr"
  1028. else
  1029. _NC="$_NC -l $ncaddr"
  1030. fi
  1031. fi
  1032. _debug "_NC" "$_NC"
  1033. # while true ; do
  1034. if [ "$DEBUG" ] ; then
  1035. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ; then
  1036. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ;
  1037. fi
  1038. else
  1039. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1; then
  1040. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1
  1041. fi
  1042. fi
  1043. if [ "$?" != "0" ] ; then
  1044. _err "nc listen error."
  1045. exit 1
  1046. fi
  1047. # done
  1048. }
  1049. _stopserver(){
  1050. pid="$1"
  1051. _debug "pid" "$pid"
  1052. if [ -z "$pid" ] ; then
  1053. return
  1054. fi
  1055. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1056. if [ "$Le_HTTPPort" ] ; then
  1057. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1058. _get "http://localhost:$Le_HTTPPort" "" 1
  1059. else
  1060. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1061. fi
  1062. fi
  1063. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1064. if [ "$Le_TLSPort" ] ; then
  1065. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1066. _get "https://localhost:$Le_TLSPort" "" 1
  1067. _get "https://localhost:$Le_TLSPort" "" 1
  1068. else
  1069. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1070. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1071. fi
  1072. fi
  1073. }
  1074. # sleep sec
  1075. _sleep() {
  1076. _sleep_sec="$1"
  1077. if [ "$__INTERACTIVE" ] ; then
  1078. _sleep_c="$_sleep_sec"
  1079. while [ "$_sleep_c" -ge "0" ] ;
  1080. do
  1081. printf "\r \r"
  1082. __green "$_sleep_c"
  1083. _sleep_c="$(_math $_sleep_c - 1)"
  1084. sleep 1
  1085. done
  1086. printf "\r"
  1087. else
  1088. sleep "$_sleep_sec"
  1089. fi
  1090. }
  1091. # _starttlsserver san_a san_b port content _ncaddr
  1092. _starttlsserver() {
  1093. _info "Starting tls server."
  1094. san_a="$1"
  1095. san_b="$2"
  1096. port="$3"
  1097. content="$4"
  1098. opaddr="$5"
  1099. _debug san_a "$san_a"
  1100. _debug san_b "$san_b"
  1101. _debug port "$port"
  1102. #create key TLS_KEY
  1103. if ! _createkey "2048" "$TLS_KEY" ; then
  1104. _err "Create tls validation key error."
  1105. return 1
  1106. fi
  1107. #create csr
  1108. alt="$san_a"
  1109. if [ "$san_b" ] ; then
  1110. alt="$alt,$san_b"
  1111. fi
  1112. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" ; then
  1113. _err "Create tls validation csr error."
  1114. return 1
  1115. fi
  1116. #self signed
  1117. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT" ; then
  1118. _err "Create tls validation cert error."
  1119. return 1
  1120. fi
  1121. __S_OPENSSL="openssl s_server -cert $TLS_CERT -key $TLS_KEY "
  1122. if [ "$opaddr" ] ; then
  1123. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1124. else
  1125. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1126. fi
  1127. _debug Le_Listen_V4 "$Le_Listen_V4"
  1128. _debug Le_Listen_V6 "$Le_Listen_V6"
  1129. if [ "$Le_Listen_V4" ] ; then
  1130. __S_OPENSSL="$__S_OPENSSL -4"
  1131. elif [ "$Le_Listen_V6" ] ; then
  1132. __S_OPENSSL="$__S_OPENSSL -6"
  1133. fi
  1134. #start openssl
  1135. _debug "$__S_OPENSSL"
  1136. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  1137. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL -tlsextdebug ) &
  1138. else
  1139. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1140. fi
  1141. serverproc="$!"
  1142. sleep 2
  1143. _debug serverproc $serverproc
  1144. }
  1145. #file
  1146. _readlink() {
  1147. _rf="$1"
  1148. if ! readlink -f "$_rf" 2>/dev/null; then
  1149. if _startswith "$_rf" "\./$PROJECT_ENTRY" ; then
  1150. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1151. return 0
  1152. fi
  1153. readlink "$_rf"
  1154. fi
  1155. }
  1156. __initHome() {
  1157. if [ -z "$_SCRIPT_HOME" ] ; then
  1158. if _exists readlink && _exists dirname ; then
  1159. _debug "Lets find script dir."
  1160. _debug "_SCRIPT_" "$_SCRIPT_"
  1161. _script="$(_readlink "$_SCRIPT_")"
  1162. _debug "_script" "$_script"
  1163. _script_home="$(dirname "$_script")"
  1164. _debug "_script_home" "$_script_home"
  1165. if [ -d "$_script_home" ] ; then
  1166. _SCRIPT_HOME="$_script_home"
  1167. else
  1168. _err "It seems the script home is not correct:$_script_home"
  1169. fi
  1170. fi
  1171. fi
  1172. if [ -z "$LE_WORKING_DIR" ] ; then
  1173. if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ] ; then
  1174. _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1175. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1176. else
  1177. LE_WORKING_DIR="$_SCRIPT_HOME"
  1178. fi
  1179. fi
  1180. if [ -z "$LE_WORKING_DIR" ] ; then
  1181. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1182. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1183. fi
  1184. export LE_WORKING_DIR
  1185. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1186. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1187. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  1188. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1189. fi
  1190. fi
  1191. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1192. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1193. fi
  1194. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1195. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1196. }
  1197. #[domain] [keylength]
  1198. _initpath() {
  1199. __initHome
  1200. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  1201. . "$ACCOUNT_CONF_PATH"
  1202. fi
  1203. if [ "$IN_CRON" ] ; then
  1204. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  1205. _USER_PATH_EXPORTED=1
  1206. export PATH="$USER_PATH:$PATH"
  1207. fi
  1208. fi
  1209. if [ -z "$CA_HOME" ] ; then
  1210. CA_HOME="$DEFAULT_CA_HOME"
  1211. fi
  1212. if [ -z "$API" ] ; then
  1213. if [ -z "$STAGE" ] ; then
  1214. API="$DEFAULT_CA"
  1215. else
  1216. API="$STAGE_CA"
  1217. _info "Using stage api:$API"
  1218. fi
  1219. fi
  1220. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1221. CA_DIR="$CA_HOME/$_API_HOST"
  1222. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1223. if [ -z "$CA_CONF" ] ; then
  1224. CA_CONF="$_DEFAULT_CA_CONF"
  1225. fi
  1226. if [ -f "$CA_CONF" ] ; then
  1227. . "$CA_CONF"
  1228. fi
  1229. if [ -z "$ACME_DIR" ] ; then
  1230. ACME_DIR="/home/.acme"
  1231. fi
  1232. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  1233. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1234. fi
  1235. if [ -z "$USER_AGENT" ] ; then
  1236. USER_AGENT="$DEFAULT_USER_AGENT"
  1237. fi
  1238. if [ -z "$HTTP_HEADER" ] ; then
  1239. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1240. fi
  1241. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1242. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1243. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1244. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1245. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  1246. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1247. fi
  1248. if [ -z "$ACCOUNT_JSON_PATH" ] ; then
  1249. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1250. fi
  1251. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1252. if [ -z "$CERT_HOME" ] ; then
  1253. CERT_HOME="$_DEFAULT_CERT_HOME"
  1254. fi
  1255. if [ -z "$1" ] ; then
  1256. return 0
  1257. fi
  1258. mkdir -p "$CA_DIR"
  1259. domain="$1"
  1260. _ilength="$2"
  1261. if [ -z "$DOMAIN_PATH" ] ; then
  1262. domainhome="$CERT_HOME/$domain"
  1263. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1264. DOMAIN_PATH="$domainhome"
  1265. if _isEccKey "$_ilength" ; then
  1266. DOMAIN_PATH="$domainhomeecc"
  1267. else
  1268. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ] ; then
  1269. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1270. fi
  1271. fi
  1272. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1273. fi
  1274. if [ ! -d "$DOMAIN_PATH" ] ; then
  1275. if ! mkdir -p "$DOMAIN_PATH" ; then
  1276. _err "Can not create domain path: $DOMAIN_PATH"
  1277. return 1
  1278. fi
  1279. fi
  1280. if [ -z "$DOMAIN_CONF" ] ; then
  1281. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1282. fi
  1283. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  1284. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1285. fi
  1286. if [ -z "$CSR_PATH" ] ; then
  1287. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1288. fi
  1289. if [ -z "$CERT_KEY_PATH" ] ; then
  1290. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1291. fi
  1292. if [ -z "$CERT_PATH" ] ; then
  1293. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1294. fi
  1295. if [ -z "$CA_CERT_PATH" ] ; then
  1296. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1297. fi
  1298. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  1299. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1300. fi
  1301. if [ -z "$CERT_PFX_PATH" ] ; then
  1302. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1303. fi
  1304. if [ -z "$TLS_CONF" ] ; then
  1305. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1306. fi
  1307. if [ -z "$TLS_CERT" ] ; then
  1308. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1309. fi
  1310. if [ -z "$TLS_KEY" ] ; then
  1311. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1312. fi
  1313. if [ -z "$TLS_CSR" ] ; then
  1314. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1315. fi
  1316. }
  1317. _apachePath() {
  1318. _APACHECTL="apachectl"
  1319. if ! _exists apachectl ; then
  1320. if _exists apache2ctl ; then
  1321. _APACHECTL="apache2ctl"
  1322. else
  1323. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1324. _err "Please use webroot mode to try again."
  1325. return 1
  1326. fi
  1327. fi
  1328. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  1329. _debug httpdconfname "$httpdconfname"
  1330. if _startswith "$httpdconfname" '/' ; then
  1331. httpdconf="$httpdconfname"
  1332. httpdconfname="$(basename $httpdconfname)"
  1333. else
  1334. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  1335. _debug httpdroot "$httpdroot"
  1336. httpdconf="$httpdroot/$httpdconfname"
  1337. httpdconfname="$(basename $httpdconfname)"
  1338. fi
  1339. _debug httpdconf "$httpdconf"
  1340. _debug httpdconfname "$httpdconfname"
  1341. if [ ! -f "$httpdconf" ] ; then
  1342. _err "Apache Config file not found" "$httpdconf"
  1343. return 1
  1344. fi
  1345. return 0
  1346. }
  1347. _restoreApache() {
  1348. if [ -z "$usingApache" ] ; then
  1349. return 0
  1350. fi
  1351. _initpath
  1352. if ! _apachePath ; then
  1353. return 1
  1354. fi
  1355. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  1356. _debug "No config file to restore."
  1357. return 0
  1358. fi
  1359. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  1360. _debug "Restored: $httpdconf."
  1361. if ! $_APACHECTL -t >/dev/null 2>&1 ; then
  1362. _err "Sorry, restore apache config error, please contact me."
  1363. return 1;
  1364. fi
  1365. _debug "Restored successfully."
  1366. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1367. return 0
  1368. }
  1369. _setApache() {
  1370. _initpath
  1371. if ! _apachePath ; then
  1372. return 1
  1373. fi
  1374. #test the conf first
  1375. _info "Checking if there is an error in the apache config file before starting."
  1376. _msg="$($_APACHECTL -t 2>&1 )"
  1377. if [ "$?" != "0" ] ; then
  1378. _err "Sorry, apache config file has error, please fix it first, then try again."
  1379. _err "Don't worry, there is nothing changed to your system."
  1380. _err "$_msg"
  1381. return 1;
  1382. else
  1383. _info "OK"
  1384. fi
  1385. #backup the conf
  1386. _debug "Backup apache config file" "$httpdconf"
  1387. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/" ; then
  1388. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1389. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1390. return 1
  1391. fi
  1392. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1393. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1394. _info "The backup file will be deleted on sucess, just forget it."
  1395. #add alias
  1396. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  1397. _debug "apacheVer" "$apacheVer"
  1398. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1399. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1400. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ] ; then
  1401. echo "
  1402. Alias /.well-known/acme-challenge $ACME_DIR
  1403. <Directory $ACME_DIR >
  1404. Require all granted
  1405. </Directory>
  1406. " >> "$httpdconf"
  1407. else
  1408. echo "
  1409. Alias /.well-known/acme-challenge $ACME_DIR
  1410. <Directory $ACME_DIR >
  1411. Order allow,deny
  1412. Allow from all
  1413. </Directory>
  1414. " >> "$httpdconf"
  1415. fi
  1416. _msg="$($_APACHECTL -t 2>&1 )"
  1417. if [ "$?" != "0" ] ; then
  1418. _err "Sorry, apache config error"
  1419. if _restoreApache ; then
  1420. _err "The apache config file is restored."
  1421. else
  1422. _err "Sorry, The apache config file can not be restored, please report bug."
  1423. fi
  1424. return 1;
  1425. fi
  1426. if [ ! -d "$ACME_DIR" ] ; then
  1427. mkdir -p "$ACME_DIR"
  1428. chmod 755 "$ACME_DIR"
  1429. fi
  1430. if ! $_APACHECTL graceful ; then
  1431. _err "Sorry, $_APACHECTL graceful error, please contact me."
  1432. _restoreApache
  1433. return 1;
  1434. fi
  1435. usingApache="1"
  1436. return 0
  1437. }
  1438. _clearup() {
  1439. _stopserver $serverproc
  1440. serverproc=""
  1441. _restoreApache
  1442. if [ -z "$DEBUG" ] ; then
  1443. rm -f "$TLS_CONF"
  1444. rm -f "$TLS_CERT"
  1445. rm -f "$TLS_KEY"
  1446. rm -f "$TLS_CSR"
  1447. fi
  1448. }
  1449. # webroot removelevel tokenfile
  1450. _clearupwebbroot() {
  1451. __webroot="$1"
  1452. if [ -z "$__webroot" ] ; then
  1453. _debug "no webroot specified, skip"
  1454. return 0
  1455. fi
  1456. _rmpath=""
  1457. if [ "$2" = '1' ] ; then
  1458. _rmpath="$__webroot/.well-known"
  1459. elif [ "$2" = '2' ] ; then
  1460. _rmpath="$__webroot/.well-known/acme-challenge"
  1461. elif [ "$2" = '3' ] ; then
  1462. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1463. else
  1464. _debug "Skip for removelevel:$2"
  1465. fi
  1466. if [ "$_rmpath" ] ; then
  1467. if [ "$DEBUG" ] ; then
  1468. _debug "Debugging, skip removing: $_rmpath"
  1469. else
  1470. rm -rf "$_rmpath"
  1471. fi
  1472. fi
  1473. return 0
  1474. }
  1475. _on_before_issue() {
  1476. _debug _on_before_issue
  1477. if _hasfield "$Le_Webroot" "$NO_VALUE" ; then
  1478. if ! _exists "nc" ; then
  1479. _err "Please install netcat(nc) tools first."
  1480. return 1
  1481. fi
  1482. elif ! _hasfield "$Le_Webroot" "$W_TLS" ; then
  1483. #no need to check anymore
  1484. return 0
  1485. fi
  1486. _debug Le_LocalAddress "$Le_LocalAddress"
  1487. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1488. _index=1
  1489. _currentRoot=""
  1490. _addrIndex=1
  1491. for d in $alldomains
  1492. do
  1493. _debug "Check for domain" $d
  1494. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1495. _debug "_currentRoot" "$_currentRoot"
  1496. _index=$(_math $_index + 1)
  1497. _checkport=""
  1498. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  1499. _info "Standalone mode."
  1500. if [ -z "$Le_HTTPPort" ] ; then
  1501. Le_HTTPPort=80
  1502. else
  1503. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1504. fi
  1505. _checkport="$Le_HTTPPort"
  1506. elif [ "$_currentRoot" = "$W_TLS" ] ; then
  1507. _info "Standalone tls mode."
  1508. if [ -z "$Le_TLSPort" ] ; then
  1509. Le_TLSPort=443
  1510. else
  1511. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1512. fi
  1513. _checkport="$Le_TLSPort"
  1514. fi
  1515. if [ "$_checkport" ] ; then
  1516. _debug _checkport "$_checkport"
  1517. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1518. _debug _checkaddr "$_checkaddr"
  1519. _addrIndex="$(_math $_addrIndex + 1)"
  1520. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1521. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1522. if [ -z "$netprc" ] ; then
  1523. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1524. fi
  1525. if [ "$netprc" ] ; then
  1526. _err "$netprc"
  1527. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1528. _err "Please stop it first"
  1529. return 1
  1530. fi
  1531. fi
  1532. done
  1533. if _hasfield "$Le_Webroot" "apache" ; then
  1534. if ! _setApache ; then
  1535. _err "set up apache error. Report error to me."
  1536. return 1
  1537. fi
  1538. else
  1539. usingApache=""
  1540. fi
  1541. #run pre hook
  1542. if [ "$Le_PreHook" ] ; then
  1543. _info "Run pre hook:'$Le_PreHook'"
  1544. if ! (
  1545. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1546. ) ; then
  1547. _err "Error when run pre hook."
  1548. return 1
  1549. fi
  1550. fi
  1551. }
  1552. _on_issue_err() {
  1553. _debug _on_issue_err
  1554. if [ "$LOG_FILE" ] ; then
  1555. _err "Please check log file for more details: $LOG_FILE"
  1556. else
  1557. _err "Please use add '--debug' or '--log' to check more details."
  1558. _err "See: $_DEBUG_WIKI"
  1559. fi
  1560. #run the post hook
  1561. if [ "$Le_PostHook" ] ; then
  1562. _info "Run post hook:'$Le_PostHook'"
  1563. if ! (
  1564. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1565. ) ; then
  1566. _err "Error when run post hook."
  1567. return 1
  1568. fi
  1569. fi
  1570. }
  1571. _on_issue_success() {
  1572. _debug _on_issue_success
  1573. #run the post hook
  1574. if [ "$Le_PostHook" ] ; then
  1575. _info "Run post hook:'$Le_PostHook'"
  1576. if ! (
  1577. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1578. ) ; then
  1579. _err "Error when run post hook."
  1580. return 1
  1581. fi
  1582. fi
  1583. #run renew hook
  1584. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ] ; then
  1585. _info "Run renew hook:'$Le_RenewHook'"
  1586. if ! (
  1587. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1588. ) ; then
  1589. _err "Error when run renew hook."
  1590. return 1
  1591. fi
  1592. fi
  1593. }
  1594. updateaccount() {
  1595. _initpath
  1596. _regAccount
  1597. }
  1598. registeraccount() {
  1599. _initpath
  1600. _regAccount
  1601. }
  1602. _regAccount() {
  1603. _initpath
  1604. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1605. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1606. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1607. fi
  1608. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1609. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1610. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1611. fi
  1612. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  1613. _acck="no"
  1614. if [ "$Le_Keylength" ] ; then
  1615. _acck="$Le_Keylength"
  1616. fi
  1617. if ! createAccountKey "$_acck" ; then
  1618. _err "Create account key error."
  1619. return 1
  1620. fi
  1621. fi
  1622. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  1623. return 1
  1624. fi
  1625. _updateTos=""
  1626. _reg_res="new-reg"
  1627. while true ;
  1628. do
  1629. _debug AGREEMENT "$AGREEMENT"
  1630. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ' )
  1631. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  1632. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1633. if [ "$ACCOUNT_EMAIL" ] ; then
  1634. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1635. fi
  1636. if [ -z "$_updateTos" ] ; then
  1637. _info "Registering account"
  1638. if ! _send_signed_request "$API/acme/new-reg" "$regjson" ; then
  1639. _err "Register account Error: $response"
  1640. return 1
  1641. fi
  1642. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  1643. echo "$response" > $ACCOUNT_JSON_PATH
  1644. _info "Registered"
  1645. elif [ "$code" = '409' ] ; then
  1646. _info "Already registered"
  1647. else
  1648. _err "Register account Error: $response"
  1649. return 1
  1650. fi
  1651. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2| tr -d "\r\n")"
  1652. _debug "_accUri" "$_accUri"
  1653. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1654. _debug "_tos" "$_tos"
  1655. if [ -z "$_tos" ] ; then
  1656. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1657. _tos="$DEFAULT_AGREEMENT"
  1658. fi
  1659. if [ "$_tos" != "$AGREEMENT" ]; then
  1660. _updateTos=1
  1661. AGREEMENT="$_tos"
  1662. _reg_res="reg"
  1663. continue
  1664. fi
  1665. else
  1666. _debug "Update tos: $_tos"
  1667. if ! _send_signed_request "$_accUri" "$regjson" ; then
  1668. _err "Update tos error."
  1669. return 1
  1670. fi
  1671. if [ "$code" = '202' ] ; then
  1672. _info "Update success."
  1673. else
  1674. _err "Update error."
  1675. return 1
  1676. fi
  1677. fi
  1678. return 0
  1679. done
  1680. }
  1681. # domain folder file
  1682. _findHook() {
  1683. _hookdomain="$1"
  1684. _hookcat="$2"
  1685. _hookname="$3"
  1686. if [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ] ; then
  1687. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  1688. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ] ; then
  1689. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  1690. elif [ -f "$LE_WORKING_DIR/$_hookname" ] ; then
  1691. d_api="$LE_WORKING_DIR/$_hookname"
  1692. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ] ; then
  1693. d_api="$LE_WORKING_DIR/$_hookname.sh"
  1694. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ] ; then
  1695. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  1696. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ] ; then
  1697. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  1698. fi
  1699. printf "%s" "$d_api"
  1700. }
  1701. #webroot, domain domainlist keylength
  1702. issue() {
  1703. if [ -z "$2" ] ; then
  1704. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  1705. return 1
  1706. fi
  1707. Le_Webroot="$1"
  1708. Le_Domain="$2"
  1709. Le_Alt="$3"
  1710. Le_Keylength="$4"
  1711. Le_RealCertPath="$5"
  1712. Le_RealKeyPath="$6"
  1713. Le_RealCACertPath="$7"
  1714. Le_ReloadCmd="$8"
  1715. Le_RealFullChainPath="$9"
  1716. Le_PreHook="${10}"
  1717. Le_PostHook="${11}"
  1718. Le_RenewHook="${12}"
  1719. Le_LocalAddress="${13}"
  1720. #remove these later.
  1721. if [ "$Le_Webroot" = "dns-cf" ] ; then
  1722. Le_Webroot="dns_cf"
  1723. fi
  1724. if [ "$Le_Webroot" = "dns-dp" ] ; then
  1725. Le_Webroot="dns_dp"
  1726. fi
  1727. if [ "$Le_Webroot" = "dns-cx" ] ; then
  1728. Le_Webroot="dns_cx"
  1729. fi
  1730. _debug "Using api: $API"
  1731. if [ ! "$IS_RENEW" ] ; then
  1732. _initpath $Le_Domain "$Le_Keylength"
  1733. mkdir -p "$DOMAIN_PATH"
  1734. fi
  1735. if [ -f "$DOMAIN_CONF" ] ; then
  1736. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  1737. _debug Le_NextRenewTime "$Le_NextRenewTime"
  1738. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(_time) -lt $Le_NextRenewTime ] ; then
  1739. _saved_domain=$(_readdomainconf Le_Domain)
  1740. _debug _saved_domain "$_saved_domain"
  1741. _saved_alt=$(_readdomainconf Le_Alt)
  1742. _debug _saved_alt "$_saved_alt"
  1743. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ] ; then
  1744. _info "Domains not changed."
  1745. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  1746. _info "Add '$(__red '--force')' to force to renew."
  1747. return $RENEW_SKIP
  1748. else
  1749. _info "Domains have changed."
  1750. fi
  1751. fi
  1752. fi
  1753. _savedomainconf "Le_Domain" "$Le_Domain"
  1754. _savedomainconf "Le_Alt" "$Le_Alt"
  1755. _savedomainconf "Le_Webroot" "$Le_Webroot"
  1756. _savedomainconf "Le_PreHook" "$Le_PreHook"
  1757. _savedomainconf "Le_PostHook" "$Le_PostHook"
  1758. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  1759. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  1760. Le_API="$API"
  1761. _savedomainconf "Le_API" "$Le_API"
  1762. if [ "$Le_Alt" = "$NO_VALUE" ] ; then
  1763. Le_Alt=""
  1764. fi
  1765. if [ "$Le_Keylength" = "$NO_VALUE" ] ; then
  1766. Le_Keylength=""
  1767. fi
  1768. if ! _on_before_issue ; then
  1769. _err "_on_before_issue."
  1770. return 1
  1771. fi
  1772. if ! _regAccount ; then
  1773. _on_issue_err
  1774. return 1
  1775. fi
  1776. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ] ; then
  1777. _info "Signing from existing CSR."
  1778. else
  1779. _key=$(_readdomainconf Le_Keylength)
  1780. _debug "Read key length:$_key"
  1781. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ] ; then
  1782. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  1783. _err "Create domain key error."
  1784. _clearup
  1785. _on_issue_err
  1786. return 1
  1787. fi
  1788. fi
  1789. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF" ; then
  1790. _err "Create CSR error."
  1791. _clearup
  1792. _on_issue_err
  1793. return 1
  1794. fi
  1795. fi
  1796. _savedomainconf "Le_Keylength" "$Le_Keylength"
  1797. vlist="$Le_Vlist"
  1798. # verify each domain
  1799. _info "Verify each domain"
  1800. sep='#'
  1801. if [ -z "$vlist" ] ; then
  1802. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1803. _index=1
  1804. _currentRoot=""
  1805. for d in $alldomains
  1806. do
  1807. _info "Getting webroot for domain" $d
  1808. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1809. _info _w "$_w"
  1810. if [ "$_w" ] ; then
  1811. _currentRoot="$_w"
  1812. fi
  1813. _debug "_currentRoot" "$_currentRoot"
  1814. _index=$(_math $_index + 1)
  1815. vtype="$VTYPE_HTTP"
  1816. if _startswith "$_currentRoot" "dns" ; then
  1817. vtype="$VTYPE_DNS"
  1818. fi
  1819. if [ "$_currentRoot" = "$W_TLS" ] ; then
  1820. vtype="$VTYPE_TLS"
  1821. fi
  1822. _info "Getting new-authz for domain" $d
  1823. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}" ; then
  1824. _err "Can not get domain token."
  1825. _clearup
  1826. _on_issue_err
  1827. return 1
  1828. fi
  1829. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1830. _err "new-authz error: $response"
  1831. _clearup
  1832. _on_issue_err
  1833. return 1
  1834. fi
  1835. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  1836. _debug entry "$entry"
  1837. if [ -z "$entry" ] ; then
  1838. _err "Error, can not get domain token $d"
  1839. _clearup
  1840. _on_issue_err
  1841. return 1
  1842. fi
  1843. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1844. _debug token $token
  1845. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1846. _debug uri $uri
  1847. keyauthorization="$token.$thumbprint"
  1848. _debug keyauthorization "$keyauthorization"
  1849. if printf "$response" | grep '"status":"valid"' >/dev/null 2>&1 ; then
  1850. _info "$d is already verified, skip."
  1851. keyauthorization=$STATE_VERIFIED
  1852. _debug keyauthorization "$keyauthorization"
  1853. fi
  1854. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1855. _debug dvlist "$dvlist"
  1856. vlist="$vlist$dvlist,"
  1857. done
  1858. #add entry
  1859. dnsadded=""
  1860. ventries=$(echo "$vlist" | tr ',' ' ' )
  1861. for ventry in $ventries
  1862. do
  1863. d=$(echo $ventry | cut -d $sep -f 1)
  1864. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1865. vtype=$(echo $ventry | cut -d $sep -f 4)
  1866. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1867. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1868. _info "$d is already verified, skip $vtype."
  1869. continue
  1870. fi
  1871. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1872. dnsadded='0'
  1873. txtdomain="_acme-challenge.$d"
  1874. _debug txtdomain "$txtdomain"
  1875. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1876. _debug txt "$txt"
  1877. d_api="$(_findHook $d dnsapi $_currentRoot)"
  1878. _debug d_api "$d_api"
  1879. if [ "$d_api" ] ; then
  1880. _info "Found domain api file: $d_api"
  1881. else
  1882. _err "Add the following TXT record:"
  1883. _err "Domain: '$(__green $txtdomain)'"
  1884. _err "TXT value: '$(__green $txt)'"
  1885. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1886. _err "so the resulting subdomain will be: $txtdomain"
  1887. continue
  1888. fi
  1889. (
  1890. if ! . $d_api ; then
  1891. _err "Load file $d_api error. Please check your api file and try again."
  1892. return 1
  1893. fi
  1894. addcommand="${_currentRoot}_add"
  1895. if ! _exists $addcommand ; then
  1896. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1897. return 1
  1898. fi
  1899. if ! $addcommand $txtdomain $txt ; then
  1900. _err "Error add txt for domain:$txtdomain"
  1901. return 1
  1902. fi
  1903. )
  1904. if [ "$?" != "0" ] ; then
  1905. _clearup
  1906. _on_issue_err
  1907. return 1
  1908. fi
  1909. dnsadded='1'
  1910. fi
  1911. done
  1912. if [ "$dnsadded" = '0' ] ; then
  1913. _savedomainconf "Le_Vlist" "$vlist"
  1914. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1915. _err "Please add the TXT records to the domains, and retry again."
  1916. _clearup
  1917. _on_issue_err
  1918. return 1
  1919. fi
  1920. fi
  1921. if [ "$dnsadded" = '1' ] ; then
  1922. if [ -z "$Le_DNSSleep" ] ; then
  1923. Le_DNSSleep=$DEFAULT_DNS_SLEEP
  1924. else
  1925. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  1926. fi
  1927. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  1928. _sleep $Le_DNSSleep
  1929. fi
  1930. _debug "ok, let's start to verify"
  1931. _ncIndex=1
  1932. ventries=$(echo "$vlist" | tr ',' ' ' )
  1933. for ventry in $ventries
  1934. do
  1935. d=$(echo $ventry | cut -d $sep -f 1)
  1936. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1937. uri=$(echo $ventry | cut -d $sep -f 3)
  1938. vtype=$(echo $ventry | cut -d $sep -f 4)
  1939. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1940. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1941. _info "$d is already verified, skip $vtype."
  1942. continue
  1943. fi
  1944. _info "Verifying:$d"
  1945. _debug "d" "$d"
  1946. _debug "keyauthorization" "$keyauthorization"
  1947. _debug "uri" "$uri"
  1948. removelevel=""
  1949. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  1950. _debug "_currentRoot" "$_currentRoot"
  1951. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1952. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  1953. _info "Standalone mode server"
  1954. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  1955. _ncIndex="$(_math $_ncIndex + 1)"
  1956. _startserver "$keyauthorization" "$_ncaddr" &
  1957. if [ "$?" != "0" ] ; then
  1958. _clearup
  1959. _on_issue_err
  1960. return 1
  1961. fi
  1962. serverproc="$!"
  1963. sleep 2
  1964. _debug serverproc $serverproc
  1965. else
  1966. if [ "$_currentRoot" = "apache" ] ; then
  1967. wellknown_path="$ACME_DIR"
  1968. else
  1969. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1970. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1971. removelevel='1'
  1972. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1973. removelevel='2'
  1974. else
  1975. removelevel='3'
  1976. fi
  1977. fi
  1978. _debug wellknown_path "$wellknown_path"
  1979. _debug "writing token:$token to $wellknown_path/$token"
  1980. mkdir -p "$wellknown_path"
  1981. printf "%s" "$keyauthorization" > "$wellknown_path/$token"
  1982. if [ ! "$usingApache" ] ; then
  1983. if webroot_owner=$(_stat $_currentRoot) ; then
  1984. _debug "Changing owner/group of .well-known to $webroot_owner"
  1985. chown -R $webroot_owner "$_currentRoot/.well-known"
  1986. else
  1987. _debug "not chaning owner/group of webroot";
  1988. fi
  1989. fi
  1990. fi
  1991. elif [ "$vtype" = "$VTYPE_TLS" ] ; then
  1992. #create A
  1993. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  1994. #_debug2 _hash_A "$_hash_A"
  1995. #_x="$(echo $_hash_A | cut -c 1-32)"
  1996. #_debug2 _x "$_x"
  1997. #_y="$(echo $_hash_A | cut -c 33-64)"
  1998. #_debug2 _y "$_y"
  1999. #_SAN_A="$_x.$_y.token.acme.invalid"
  2000. #_debug2 _SAN_A "$_SAN_A"
  2001. #create B
  2002. _hash_B="$(printf "%s" $keyauthorization | _digest "sha256" "hex" )"
  2003. _debug2 _hash_B "$_hash_B"
  2004. _x="$(echo $_hash_B | cut -c 1-32)"
  2005. _debug2 _x "$_x"
  2006. _y="$(echo $_hash_B | cut -c 33-64)"
  2007. _debug2 _y "$_y"
  2008. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2009. _SAN_B="$_x.$_y.acme.invalid"
  2010. _debug2 _SAN_B "$_SAN_B"
  2011. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  2012. _ncIndex="$(_math $_ncIndex + 1)"
  2013. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2014. _err "Start tls server error."
  2015. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2016. _clearup
  2017. _on_issue_err
  2018. return 1
  2019. fi
  2020. fi
  2021. if ! _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}" ; then
  2022. _err "$d:Can not get challenge: $response"
  2023. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2024. _clearup
  2025. _on_issue_err
  2026. return 1
  2027. fi
  2028. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  2029. _err "$d:Challenge error: $response"
  2030. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2031. _clearup
  2032. _on_issue_err
  2033. return 1
  2034. fi
  2035. waittimes=0
  2036. if [ -z "$MAX_RETRY_TIMES" ] ; then
  2037. MAX_RETRY_TIMES=30
  2038. fi
  2039. while true ; do
  2040. waittimes=$(_math $waittimes + 1)
  2041. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  2042. _err "$d:Timeout"
  2043. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2044. _clearup
  2045. _on_issue_err
  2046. return 1
  2047. fi
  2048. _debug "sleep 5 secs to verify"
  2049. sleep 5
  2050. _debug "checking"
  2051. response="$(_get $uri)"
  2052. if [ "$?" != "0" ] ; then
  2053. _err "$d:Verify error:$response"
  2054. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2055. _clearup
  2056. _on_issue_err
  2057. return 1
  2058. fi
  2059. _debug2 original "$response"
  2060. response="$(echo "$response" | _normalizeJson )"
  2061. _debug2 response "$response"
  2062. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2063. if [ "$status" = "valid" ] ; then
  2064. _info "Success"
  2065. _stopserver $serverproc
  2066. serverproc=""
  2067. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2068. break;
  2069. fi
  2070. if [ "$status" = "invalid" ] ; then
  2071. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2072. _debug2 error "$error"
  2073. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2074. _debug2 errordetail "$errordetail"
  2075. if [ "$errordetail" ] ; then
  2076. _err "$d:Verify error:$errordetail"
  2077. else
  2078. _err "$d:Verify error:$error"
  2079. fi
  2080. if [ "$DEBUG" ] ; then
  2081. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  2082. _debug "Debug: get token url."
  2083. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2084. fi
  2085. fi
  2086. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2087. _clearup
  2088. _on_issue_err
  2089. return 1;
  2090. fi
  2091. if [ "$status" = "pending" ] ; then
  2092. _info "Pending"
  2093. else
  2094. _err "$d:Verify error:$response"
  2095. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2096. _clearup
  2097. _on_issue_err
  2098. return 1
  2099. fi
  2100. done
  2101. done
  2102. _clearup
  2103. _info "Verify finished, start to sign."
  2104. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2105. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64" ; then
  2106. _err "Sign failed."
  2107. _on_issue_err
  2108. return 1
  2109. fi
  2110. _rcert="$response"
  2111. Le_LinkCert="$(grep -i '^Location.*$' $HTTP_HEADER | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2112. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2113. if [ "$Le_LinkCert" ] ; then
  2114. echo "$BEGIN_CERT" > "$CERT_PATH"
  2115. if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2116. _debug "Get cert failed. Let's try last response."
  2117. printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2118. fi
  2119. echo "$END_CERT" >> "$CERT_PATH"
  2120. _info "$(__green "Cert success.")"
  2121. cat "$CERT_PATH"
  2122. _info "Your cert is in $( __green " $CERT_PATH ")"
  2123. if [ -f "$CERT_KEY_PATH" ] ; then
  2124. _info "Your cert key is in $( __green " $CERT_KEY_PATH ")"
  2125. fi
  2126. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2127. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  2128. USER_PATH="$PATH"
  2129. _saveaccountconf "USER_PATH" "$USER_PATH"
  2130. fi
  2131. fi
  2132. if [ -z "$Le_LinkCert" ] ; then
  2133. response="$(echo $response | _dbase64 "multiline" | _normalizeJson )"
  2134. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2135. _on_issue_err
  2136. return 1
  2137. fi
  2138. _cleardomainconf "Le_Vlist"
  2139. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | _head_n 1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  2140. if ! _contains "$Le_LinkIssuer" ":" ; then
  2141. Le_LinkIssuer="$API$Le_LinkIssuer"
  2142. fi
  2143. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2144. if [ "$Le_LinkIssuer" ] ; then
  2145. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  2146. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  2147. echo "$END_CERT" >> "$CA_CERT_PATH"
  2148. _info "The intermediate CA cert is in $( __green " $CA_CERT_PATH ")"
  2149. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  2150. _info "And the full chain certs is there: $( __green " $CERT_FULLCHAIN_PATH ")"
  2151. fi
  2152. Le_CertCreateTime=$(_time)
  2153. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2154. Le_CertCreateTimeStr=$(date -u )
  2155. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2156. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ] ; then
  2157. Le_RenewalDays=$MAX_RENEW
  2158. else
  2159. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2160. fi
  2161. if [ "$CA_BUNDLE" ] ; then
  2162. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2163. else
  2164. _clearaccountconf "CA_BUNDLE"
  2165. fi
  2166. if [ "$HTTPS_INSECURE" ] ; then
  2167. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2168. else
  2169. _clearaccountconf "HTTPS_INSECURE"
  2170. fi
  2171. if [ "$Le_Listen_V4" ] ; then
  2172. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2173. _cleardomainconf Le_Listen_V6
  2174. elif [ "$Le_Listen_V6" ] ; then
  2175. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2176. _cleardomainconf Le_Listen_V4
  2177. fi
  2178. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  2179. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  2180. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2181. Le_NextRenewTime=$(_math $Le_NextRenewTime - 86400)
  2182. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2183. _on_issue_success
  2184. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ] ; then
  2185. _installcert
  2186. fi
  2187. }
  2188. #domain [isEcc]
  2189. renew() {
  2190. Le_Domain="$1"
  2191. if [ -z "$Le_Domain" ] ; then
  2192. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2193. return 1
  2194. fi
  2195. _isEcc="$2"
  2196. _initpath $Le_Domain "$_isEcc"
  2197. _info "$(__green "Renew: '$Le_Domain'")"
  2198. if [ ! -f "$DOMAIN_CONF" ] ; then
  2199. _info "'$Le_Domain' is not a issued domain, skip."
  2200. return 0;
  2201. fi
  2202. if [ "$Le_RenewalDays" ] ; then
  2203. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2204. fi
  2205. . "$DOMAIN_CONF"
  2206. if [ "$Le_API" ] ; then
  2207. API="$Le_API"
  2208. fi
  2209. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ] ; then
  2210. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2211. _info "Add '$(__red '--force')' to force to renew."
  2212. return $RENEW_SKIP
  2213. fi
  2214. IS_RENEW="1"
  2215. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2216. res=$?
  2217. if [ "$res" != "0" ] ; then
  2218. return $res
  2219. fi
  2220. if [ "$Le_DeployHook" ] ; then
  2221. deploy $Le_Domain "$Le_DeployHook" "$Le_Keylength"
  2222. res=$?
  2223. fi
  2224. IS_RENEW=""
  2225. return $res
  2226. }
  2227. #renewAll [stopRenewOnError]
  2228. renewAll() {
  2229. _initpath
  2230. _stopRenewOnError="$1"
  2231. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2232. _ret="0"
  2233. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2234. d=$(echo $d | cut -d '/' -f 1)
  2235. (
  2236. if _endswith $d "$ECC_SUFFIX" ; then
  2237. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2238. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2239. fi
  2240. renew "$d" "$_isEcc"
  2241. )
  2242. rc="$?"
  2243. _debug "Return code: $rc"
  2244. if [ "$rc" != "0" ] ; then
  2245. if [ "$rc" = "$RENEW_SKIP" ] ; then
  2246. _info "Skipped $d"
  2247. elif [ "$_stopRenewOnError" ] ; then
  2248. _err "Error renew $d, stop now."
  2249. return $rc
  2250. else
  2251. _ret="$rc"
  2252. _err "Error renew $d, Go ahead to next one."
  2253. fi
  2254. fi
  2255. done
  2256. return $_ret
  2257. }
  2258. #csr webroot
  2259. signcsr(){
  2260. _csrfile="$1"
  2261. _csrW="$2"
  2262. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2263. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2264. return 1
  2265. fi
  2266. _initpath
  2267. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2268. if [ "$?" != "0" ] ; then
  2269. _err "Can not read subject from csr: $_csrfile"
  2270. return 1
  2271. fi
  2272. _debug _csrsubj "$_csrsubj"
  2273. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2274. if [ "$?" != "0" ] ; then
  2275. _err "Can not read domain list from csr: $_csrfile"
  2276. return 1
  2277. fi
  2278. _debug "_csrdomainlist" "$_csrdomainlist"
  2279. if [ -z "$_csrsubj" ] ; then
  2280. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2281. _debug _csrsubj "$_csrsubj"
  2282. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2283. _debug "_csrdomainlist" "$_csrdomainlist"
  2284. fi
  2285. if [ -z "$_csrsubj" ] ; then
  2286. _err "Can not read subject from csr: $_csrfile"
  2287. return 1
  2288. fi
  2289. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2290. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2291. _err "Can not read key length from csr: $_csrfile"
  2292. return 1
  2293. fi
  2294. _initpath "$_csrsubj" "$_csrkeylength"
  2295. mkdir -p "$DOMAIN_PATH"
  2296. _info "Copy csr to: $CSR_PATH"
  2297. cp "$_csrfile" "$CSR_PATH"
  2298. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2299. }
  2300. showcsr() {
  2301. _csrfile="$1"
  2302. _csrd="$2"
  2303. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2304. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2305. return 1
  2306. fi
  2307. _initpath
  2308. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2309. if [ "$?" != "0" ] || [ -z "$_csrsubj" ] ; then
  2310. _err "Can not read subject from csr: $_csrfile"
  2311. return 1
  2312. fi
  2313. _info "Subject=$_csrsubj"
  2314. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2315. if [ "$?" != "0" ] ; then
  2316. _err "Can not read domain list from csr: $_csrfile"
  2317. return 1
  2318. fi
  2319. _debug "_csrdomainlist" "$_csrdomainlist"
  2320. _info "SubjectAltNames=$_csrdomainlist"
  2321. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2322. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2323. _err "Can not read key length from csr: $_csrfile"
  2324. return 1
  2325. fi
  2326. _info "KeyLength=$_csrkeylength"
  2327. }
  2328. list() {
  2329. _raw="$1"
  2330. _initpath
  2331. _sep="|"
  2332. if [ "$_raw" ] ; then
  2333. printf "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew\n"
  2334. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2335. d=$(echo $d | cut -d '/' -f 1)
  2336. (
  2337. if _endswith $d "$ECC_SUFFIX" ; then
  2338. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2339. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2340. fi
  2341. _initpath $d "$_isEcc"
  2342. if [ -f "$DOMAIN_CONF" ] ; then
  2343. . "$DOMAIN_CONF"
  2344. printf "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr\n"
  2345. fi
  2346. )
  2347. done
  2348. else
  2349. if _exists column ; then
  2350. list "raw" | column -t -s "$_sep"
  2351. else
  2352. list "raw" | tr "$_sep" '\t'
  2353. fi
  2354. fi
  2355. }
  2356. deploy() {
  2357. Le_Domain="$1"
  2358. Le_DeployHook="$2"
  2359. _isEcc="$3"
  2360. if [ -z "$Le_DeployHook" ] ; then
  2361. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2362. return 1
  2363. fi
  2364. _initpath $Le_Domain "$_isEcc"
  2365. if [ ! -d "$DOMAIN_PATH" ] ; then
  2366. _err "Domain is not valid:'$Le_Domain'"
  2367. return 1
  2368. fi
  2369. _deployApi="$(_findHook $Le_Domain deploy $Le_DeployHook)"
  2370. if [ -z "$_deployApi" ] ; then
  2371. _err "The deploy hook $Le_DeployHook is not found."
  2372. return 1
  2373. fi
  2374. _debug _deployApi "$_deployApi"
  2375. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2376. if ! (
  2377. if ! . $_deployApi ; then
  2378. _err "Load file $_deployApi error. Please check your api file and try again."
  2379. return 1
  2380. fi
  2381. d_command="${Le_DeployHook}_deploy"
  2382. if ! _exists $d_command ; then
  2383. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2384. return 1
  2385. fi
  2386. if ! $d_command $Le_Domain "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH" ; then
  2387. _err "Error deploy for domain:$Le_Domain"
  2388. _on_issue_err
  2389. return 1
  2390. fi
  2391. ) ; then
  2392. _err "Deploy error."
  2393. return 1
  2394. else
  2395. _info "$(__green Success)"
  2396. fi
  2397. }
  2398. installcert() {
  2399. Le_Domain="$1"
  2400. if [ -z "$Le_Domain" ] ; then
  2401. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2402. return 1
  2403. fi
  2404. Le_RealCertPath="$2"
  2405. Le_RealKeyPath="$3"
  2406. Le_RealCACertPath="$4"
  2407. Le_ReloadCmd="$5"
  2408. Le_RealFullChainPath="$6"
  2409. _isEcc="$7"
  2410. _initpath $Le_Domain "$_isEcc"
  2411. if [ ! -d "$DOMAIN_PATH" ] ; then
  2412. _err "Domain is not valid:'$Le_Domain'"
  2413. return 1
  2414. fi
  2415. _installcert
  2416. }
  2417. _installcert() {
  2418. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2419. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2420. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2421. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2422. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2423. if [ "$Le_RealCertPath" = "$NO_VALUE" ] ; then
  2424. Le_RealCertPath=""
  2425. fi
  2426. if [ "$Le_RealKeyPath" = "$NO_VALUE" ] ; then
  2427. Le_RealKeyPath=""
  2428. fi
  2429. if [ "$Le_RealCACertPath" = "$NO_VALUE" ] ; then
  2430. Le_RealCACertPath=""
  2431. fi
  2432. if [ "$Le_ReloadCmd" = "$NO_VALUE" ] ; then
  2433. Le_ReloadCmd=""
  2434. fi
  2435. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ] ; then
  2436. Le_RealFullChainPath=""
  2437. fi
  2438. _installed="0"
  2439. if [ "$Le_RealCertPath" ] ; then
  2440. _installed=1
  2441. _info "Installing cert to:$Le_RealCertPath"
  2442. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ] ; then
  2443. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2444. fi
  2445. cat "$CERT_PATH" > "$Le_RealCertPath"
  2446. fi
  2447. if [ "$Le_RealCACertPath" ] ; then
  2448. _installed=1
  2449. _info "Installing CA to:$Le_RealCACertPath"
  2450. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  2451. echo "" >> "$Le_RealCACertPath"
  2452. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  2453. else
  2454. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ] ; then
  2455. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2456. fi
  2457. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  2458. fi
  2459. fi
  2460. if [ "$Le_RealKeyPath" ] ; then
  2461. _installed=1
  2462. _info "Installing key to:$Le_RealKeyPath"
  2463. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ] ; then
  2464. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2465. fi
  2466. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  2467. fi
  2468. if [ "$Le_RealFullChainPath" ] ; then
  2469. _installed=1
  2470. _info "Installing full chain to:$Le_RealFullChainPath"
  2471. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ] ; then
  2472. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2473. fi
  2474. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  2475. fi
  2476. if [ "$Le_ReloadCmd" ] ; then
  2477. _installed=1
  2478. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2479. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  2480. _info "$(__green "Reload success")"
  2481. else
  2482. _err "Reload error for :$Le_Domain"
  2483. fi
  2484. fi
  2485. }
  2486. installcronjob() {
  2487. _initpath
  2488. if ! _exists "crontab" ; then
  2489. _err "crontab doesn't exist, so, we can not install cron jobs."
  2490. _err "All your certs will not be renewed automatically."
  2491. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2492. return 1
  2493. fi
  2494. _info "Installing cron job"
  2495. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  2496. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  2497. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2498. else
  2499. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2500. return 1
  2501. fi
  2502. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2503. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab --
  2504. else
  2505. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  2506. fi
  2507. fi
  2508. if [ "$?" != "0" ] ; then
  2509. _err "Install cron job failed. You need to manually renew your certs."
  2510. _err "Or you can add cronjob by yourself:"
  2511. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2512. return 1
  2513. fi
  2514. }
  2515. uninstallcronjob() {
  2516. if ! _exists "crontab" ; then
  2517. return
  2518. fi
  2519. _info "Removing cron job"
  2520. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2521. if [ "$cr" ] ; then
  2522. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2523. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2524. else
  2525. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2526. fi
  2527. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2528. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2529. fi
  2530. _initpath
  2531. }
  2532. revoke() {
  2533. Le_Domain="$1"
  2534. if [ -z "$Le_Domain" ] ; then
  2535. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2536. return 1
  2537. fi
  2538. _isEcc="$2"
  2539. _initpath $Le_Domain "$_isEcc"
  2540. if [ ! -f "$DOMAIN_CONF" ] ; then
  2541. _err "$Le_Domain is not a issued domain, skip."
  2542. return 1;
  2543. fi
  2544. if [ ! -f "$CERT_PATH" ] ; then
  2545. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2546. return 1
  2547. fi
  2548. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  2549. if [ -z "$cert" ] ; then
  2550. _err "Cert for $Le_Domain is empty found, skip."
  2551. return 1
  2552. fi
  2553. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2554. uri="$API/acme/revoke-cert"
  2555. _info "Try domain key first."
  2556. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  2557. if [ -z "$response" ] ; then
  2558. _info "Revoke success."
  2559. rm -f $CERT_PATH
  2560. return 0
  2561. else
  2562. _err "Revoke error by domain key."
  2563. _err "$response"
  2564. fi
  2565. fi
  2566. _info "Then try account key."
  2567. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  2568. if [ -z "$response" ] ; then
  2569. _info "Revoke success."
  2570. rm -f $CERT_PATH
  2571. return 0
  2572. else
  2573. _err "Revoke error."
  2574. _debug "$response"
  2575. fi
  2576. fi
  2577. return 1
  2578. }
  2579. #domain vtype
  2580. _deactivate() {
  2581. _d_domain="$1"
  2582. _d_type="$2"
  2583. _initpath
  2584. _d_i=0
  2585. _d_max_retry=9
  2586. while [ "$_d_i" -lt "$_d_max_retry" ] ;
  2587. do
  2588. _info "Deactivate: $_d_domain"
  2589. _d_i="$(_math $_d_i + 1)"
  2590. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$_d_domain\"}}" ; then
  2591. _err "Can not get domain token."
  2592. return 1
  2593. fi
  2594. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2595. _debug "authzUri" "$authzUri"
  2596. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  2597. _err "new-authz error: $response"
  2598. return 1
  2599. fi
  2600. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
  2601. _debug entry "$entry"
  2602. if [ -z "$entry" ] ; then
  2603. _info "No more valid entry found."
  2604. break
  2605. fi
  2606. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2607. _debug _vtype $_vtype
  2608. _info "Found $_vtype"
  2609. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  2610. _debug uri $uri
  2611. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ] ; then
  2612. _info "Skip $_vtype"
  2613. continue
  2614. fi
  2615. _info "Deactivate: $_vtype"
  2616. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}" ; then
  2617. _err "Can not deactivate $_vtype."
  2618. return 1
  2619. fi
  2620. _info "Deactivate: $_vtype success."
  2621. done
  2622. _debug "$_d_i"
  2623. if [ "$_d_i" -lt "$_d_max_retry" ] ; then
  2624. _info "Deactivated success!"
  2625. else
  2626. _err "Deactivate failed."
  2627. fi
  2628. }
  2629. deactivate() {
  2630. _d_domain_list="$1"
  2631. _d_type="$2"
  2632. _initpath
  2633. _debug _d_domain_list "$_d_domain_list"
  2634. if [ -z "$(echo $_d_domain_list | cut -d , -f 1 )" ] ; then
  2635. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2636. return 1
  2637. fi
  2638. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' ' ) ;
  2639. do
  2640. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ] ; then
  2641. continue
  2642. fi
  2643. if ! _deactivate "$_d_dm" $_d_type ; then
  2644. return 1
  2645. fi
  2646. done
  2647. }
  2648. # Detect profile file if not specified as environment variable
  2649. _detect_profile() {
  2650. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  2651. echo "$PROFILE"
  2652. return
  2653. fi
  2654. DETECTED_PROFILE=''
  2655. SHELLTYPE="$(basename "/$SHELL")"
  2656. if [ "$SHELLTYPE" = "bash" ] ; then
  2657. if [ -f "$HOME/.bashrc" ] ; then
  2658. DETECTED_PROFILE="$HOME/.bashrc"
  2659. elif [ -f "$HOME/.bash_profile" ] ; then
  2660. DETECTED_PROFILE="$HOME/.bash_profile"
  2661. fi
  2662. elif [ "$SHELLTYPE" = "zsh" ] ; then
  2663. DETECTED_PROFILE="$HOME/.zshrc"
  2664. fi
  2665. if [ -z "$DETECTED_PROFILE" ] ; then
  2666. if [ -f "$HOME/.profile" ] ; then
  2667. DETECTED_PROFILE="$HOME/.profile"
  2668. elif [ -f "$HOME/.bashrc" ] ; then
  2669. DETECTED_PROFILE="$HOME/.bashrc"
  2670. elif [ -f "$HOME/.bash_profile" ] ; then
  2671. DETECTED_PROFILE="$HOME/.bash_profile"
  2672. elif [ -f "$HOME/.zshrc" ] ; then
  2673. DETECTED_PROFILE="$HOME/.zshrc"
  2674. fi
  2675. fi
  2676. if [ ! -z "$DETECTED_PROFILE" ] ; then
  2677. echo "$DETECTED_PROFILE"
  2678. fi
  2679. }
  2680. _initconf() {
  2681. _initpath
  2682. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2683. echo "#ACCOUNT_CONF_PATH=xxxx
  2684. #Account configurations:
  2685. #Here are the supported macros, uncomment them to make them take effect.
  2686. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  2687. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  2688. #CERT_HOME=\"/path/to/cert/home\"
  2689. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  2690. #LOG_LEVEL=1
  2691. #AUTO_UPGRADE=\"1\"
  2692. #STAGE=1 # Use the staging api
  2693. #FORCE=1 # Force to issue cert
  2694. #DEBUG=1 # Debug mode
  2695. #USER_AGENT=\"$USER_AGENT\"
  2696. #USER_PATH=""
  2697. #dns api
  2698. #######################
  2699. #Cloudflare:
  2700. #api key
  2701. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  2702. #account email
  2703. #CF_Email=\"xxxx@sss.com\"
  2704. #######################
  2705. #Dnspod.cn:
  2706. #api key id
  2707. #DP_Id=\"1234\"
  2708. #api key
  2709. #DP_Key=\"sADDsdasdgdsf\"
  2710. #######################
  2711. #Cloudxns.com:
  2712. #CX_Key=\"1234\"
  2713. #
  2714. #CX_Secret=\"sADDsdasdgdsf\"
  2715. #######################
  2716. #Godaddy.com:
  2717. #GD_Key=\"sdfdsgdgdfdasfds\"
  2718. #
  2719. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  2720. #######################
  2721. #PowerDNS:
  2722. #PDNS_Url=\"http://ns.example.com:8081\"
  2723. #PDNS_ServerId=\"localhost\"
  2724. #PDNS_Token=\"0123456789ABCDEF\"
  2725. #PDNS_Ttl=60
  2726. " > $ACCOUNT_CONF_PATH
  2727. fi
  2728. }
  2729. # nocron
  2730. _precheck() {
  2731. _nocron="$1"
  2732. if ! _exists "curl" && ! _exists "wget"; then
  2733. _err "Please install curl or wget first, we need to access http resources."
  2734. return 1
  2735. fi
  2736. if [ -z "$_nocron" ] ; then
  2737. if ! _exists "crontab" ; then
  2738. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  2739. _err "We need to set cron job to renew the certs automatically."
  2740. _err "Otherwise, your certs will not be able to be renewed automatically."
  2741. if [ -z "$FORCE" ] ; then
  2742. _err "Please add '--force' and try install again to go without crontab."
  2743. _err "./$PROJECT_ENTRY --install --force"
  2744. return 1
  2745. fi
  2746. fi
  2747. fi
  2748. if ! _exists "openssl" ; then
  2749. _err "Please install openssl first."
  2750. _err "We need openssl to generate keys."
  2751. return 1
  2752. fi
  2753. if ! _exists "nc" ; then
  2754. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  2755. _err "We use nc for standalone server if you use standalone mode."
  2756. _err "If you don't use standalone mode, just ignore this warning."
  2757. fi
  2758. return 0
  2759. }
  2760. _setShebang() {
  2761. _file="$1"
  2762. _shebang="$2"
  2763. if [ -z "$_shebang" ] ; then
  2764. _usage "Usage: file shebang"
  2765. return 1
  2766. fi
  2767. cp "$_file" "$_file.tmp"
  2768. echo "$_shebang" > "$_file"
  2769. sed -n 2,99999p "$_file.tmp" >> "$_file"
  2770. rm -f "$_file.tmp"
  2771. }
  2772. _installalias() {
  2773. _initpath
  2774. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2775. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  2776. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  2777. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  2778. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  2779. fi
  2780. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  2781. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2782. _profile="$(_detect_profile)"
  2783. if [ "$_profile" ] ; then
  2784. _debug "Found profile: $_profile"
  2785. _setopt "$_profile" ". \"$_envfile\""
  2786. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  2787. else
  2788. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  2789. fi
  2790. #for csh
  2791. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  2792. _csh_profile="$HOME/.cshrc"
  2793. if [ -f "$_csh_profile" ] ; then
  2794. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2795. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2796. _setopt "$_csh_profile" "source \"$_cshfile\""
  2797. fi
  2798. #for tcsh
  2799. _tcsh_profile="$HOME/.tcshrc"
  2800. if [ -f "$_tcsh_profile" ] ; then
  2801. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2802. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2803. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  2804. fi
  2805. }
  2806. # nocron
  2807. install() {
  2808. if [ -z "$LE_WORKING_DIR" ] ; then
  2809. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2810. fi
  2811. _nocron="$1"
  2812. if ! _initpath ; then
  2813. _err "Install failed."
  2814. return 1
  2815. fi
  2816. if [ "$_nocron" ] ; then
  2817. _debug "Skip install cron job"
  2818. fi
  2819. if ! _precheck "$_nocron" ; then
  2820. _err "Pre-check failed, can not install."
  2821. return 1
  2822. fi
  2823. #convert from le
  2824. if [ -d "$HOME/.le" ] ; then
  2825. for envfile in "le.env" "le.sh.env"
  2826. do
  2827. if [ -f "$HOME/.le/$envfile" ] ; then
  2828. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  2829. _upgrading="1"
  2830. _info "You are upgrading from le.sh"
  2831. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  2832. mv "$HOME/.le" "$LE_WORKING_DIR"
  2833. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2834. break;
  2835. fi
  2836. fi
  2837. done
  2838. fi
  2839. _info "Installing to $LE_WORKING_DIR"
  2840. if ! mkdir -p "$LE_WORKING_DIR" ; then
  2841. _err "Can not create working dir: $LE_WORKING_DIR"
  2842. return 1
  2843. fi
  2844. chmod 700 "$LE_WORKING_DIR"
  2845. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  2846. if [ "$?" != "0" ] ; then
  2847. _err "Install failed, can not copy $PROJECT_ENTRY"
  2848. return 1
  2849. fi
  2850. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  2851. _installalias
  2852. for subf in $_SUB_FOLDERS ; do
  2853. if [ -d "$subf" ] ; then
  2854. mkdir -p $LE_WORKING_DIR/$subf
  2855. cp $subf/* $LE_WORKING_DIR/$subf/
  2856. fi
  2857. done
  2858. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2859. _initconf
  2860. fi
  2861. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  2862. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  2863. fi
  2864. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  2865. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  2866. fi
  2867. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  2868. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  2869. fi
  2870. if [ -z "$_nocron" ] ; then
  2871. installcronjob
  2872. fi
  2873. if [ -z "$NO_DETECT_SH" ] ; then
  2874. #Modify shebang
  2875. if _exists bash ; then
  2876. _info "Good, bash is found, so change the shebang to use bash as prefered."
  2877. _shebang='#!/usr/bin/env bash'
  2878. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  2879. for subf in $_SUB_FOLDERS ; do
  2880. if [ -d "$LE_WORKING_DIR/$subf" ] ; then
  2881. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh ; do
  2882. _setShebang "$_apifile" "$_shebang"
  2883. done
  2884. fi
  2885. done
  2886. fi
  2887. fi
  2888. _info OK
  2889. }
  2890. # nocron
  2891. uninstall() {
  2892. _nocron="$1"
  2893. if [ -z "$_nocron" ] ; then
  2894. uninstallcronjob
  2895. fi
  2896. _initpath
  2897. _profile="$(_detect_profile)"
  2898. if [ "$_profile" ] ; then
  2899. text="$(cat $_profile)"
  2900. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  2901. fi
  2902. _csh_profile="$HOME/.cshrc"
  2903. if [ -f "$_csh_profile" ] ; then
  2904. text="$(cat $_csh_profile)"
  2905. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  2906. fi
  2907. _tcsh_profile="$HOME/.tcshrc"
  2908. if [ -f "$_tcsh_profile" ] ; then
  2909. text="$(cat $_tcsh_profile)"
  2910. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_tcsh_profile"
  2911. fi
  2912. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  2913. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  2914. }
  2915. cron() {
  2916. IN_CRON=1
  2917. _initpath
  2918. if [ "$AUTO_UPGRADE" = "1" ] ; then
  2919. export LE_WORKING_DIR
  2920. (
  2921. if ! upgrade ; then
  2922. _err "Cron:Upgrade failed!"
  2923. return 1
  2924. fi
  2925. )
  2926. . $LE_WORKING_DIR/$PROJECT_ENTRY >/dev/null
  2927. if [ -t 1 ] ; then
  2928. __INTERACTIVE="1"
  2929. fi
  2930. _info "Auto upgraded to: $VER"
  2931. fi
  2932. renewAll
  2933. _ret="$?"
  2934. IN_CRON=""
  2935. exit $_ret
  2936. }
  2937. version() {
  2938. echo "$PROJECT"
  2939. echo "v$VER"
  2940. }
  2941. showhelp() {
  2942. _initpath
  2943. version
  2944. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  2945. Commands:
  2946. --help, -h Show this help message.
  2947. --version, -v Show version info.
  2948. --install Install $PROJECT_NAME to your system.
  2949. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  2950. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  2951. --issue Issue a cert.
  2952. --signcsr Issue a cert from an existing csr.
  2953. --deploy Deploy the cert to your server.
  2954. --installcert Install the issued cert to apache/nginx or any other server.
  2955. --renew, -r Renew a cert.
  2956. --renewAll Renew all the certs.
  2957. --revoke Revoke a cert.
  2958. --list List all the certs.
  2959. --showcsr Show the content of a csr.
  2960. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  2961. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  2962. --cron Run cron job to renew all the certs.
  2963. --toPkcs Export the certificate and key to a pfx file.
  2964. --updateaccount Update account info.
  2965. --registeraccount Register account key.
  2966. --createAccountKey, -cak Create an account private key, professional use.
  2967. --createDomainKey, -cdk Create an domain private key, professional use.
  2968. --createCSR, -ccsr Create CSR , professional use.
  2969. --deactivate Deactivate the domain authz, professional use.
  2970. Parameters:
  2971. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  2972. --force, -f Used to force to install or force to renew a cert immediately.
  2973. --staging, --test Use staging server, just for test.
  2974. --debug Output debug info.
  2975. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  2976. --standalone Use standalone mode.
  2977. --tls Use standalone tls mode.
  2978. --apache Use apache mode.
  2979. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  2980. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  2981. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  2982. --accountkeylength, -ak [2048] Specifies the account key length.
  2983. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  2984. --log-level 1|2 Specifies the log level, default is 1.
  2985. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  2986. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  2987. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  2988. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  2989. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  2990. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  2991. --accountconf Specifies a customized account config file.
  2992. --home Specifies the home dir for $PROJECT_NAME .
  2993. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  2994. --useragent Specifies the user agent string. it will be saved for future use too.
  2995. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  2996. --accountkey Specifies the account key path, Only valid for the '--install' command.
  2997. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  2998. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2999. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3000. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3001. --listraw Only used for '--list' command, list the certs in raw format.
  3002. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  3003. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3004. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3005. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3006. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3007. --csr Specifies the input csr.
  3008. --pre-hook Command to be run before obtaining any certificates.
  3009. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3010. --renew-hook Command to be run once for each successfully renewed certificate.
  3011. --deploy-hook The hook file to deploy cert
  3012. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3013. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3014. --listen-v4 Force standalone/tls server to listen at ipv4.
  3015. --listen-v6 Force standalone/tls server to listen at ipv6.
  3016. "
  3017. }
  3018. # nocron
  3019. _installOnline() {
  3020. _info "Installing from online archive."
  3021. _nocron="$1"
  3022. if [ ! "$BRANCH" ] ; then
  3023. BRANCH="master"
  3024. fi
  3025. target="$PROJECT/archive/$BRANCH.tar.gz"
  3026. _info "Downloading $target"
  3027. localname="$BRANCH.tar.gz"
  3028. if ! _get "$target" > $localname ; then
  3029. _err "Download error."
  3030. return 1
  3031. fi
  3032. (
  3033. _info "Extracting $localname"
  3034. tar xzf $localname
  3035. cd "$PROJECT_NAME-$BRANCH"
  3036. chmod +x $PROJECT_ENTRY
  3037. if ./$PROJECT_ENTRY install "$_nocron" ; then
  3038. _info "Install success!"
  3039. fi
  3040. cd ..
  3041. rm -rf "$PROJECT_NAME-$BRANCH"
  3042. rm -f "$localname"
  3043. )
  3044. }
  3045. upgrade() {
  3046. if (
  3047. _initpath
  3048. export LE_WORKING_DIR
  3049. cd "$LE_WORKING_DIR"
  3050. _installOnline "nocron"
  3051. ) ; then
  3052. _info "Upgrade success!"
  3053. exit 0
  3054. else
  3055. _err "Upgrade failed!"
  3056. exit 1
  3057. fi
  3058. }
  3059. _processAccountConf() {
  3060. if [ "$_useragent" ] ; then
  3061. _saveaccountconf "USER_AGENT" "$_useragent"
  3062. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ] ; then
  3063. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3064. fi
  3065. if [ "$_accountemail" ] ; then
  3066. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3067. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ] ; then
  3068. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3069. fi
  3070. if [ "$_auto_upgrade" ] ; then
  3071. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3072. elif [ "$AUTO_UPGRADE" ] ; then
  3073. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3074. fi
  3075. }
  3076. _process() {
  3077. _CMD=""
  3078. _domain=""
  3079. _altdomains="$NO_VALUE"
  3080. _webroot=""
  3081. _keylength=""
  3082. _accountkeylength=""
  3083. _certpath=""
  3084. _keypath=""
  3085. _capath=""
  3086. _fullchainpath=""
  3087. _reloadcmd=""
  3088. _password=""
  3089. _accountconf=""
  3090. _useragent=""
  3091. _accountemail=""
  3092. _accountkey=""
  3093. _certhome=""
  3094. _httpport=""
  3095. _tlsport=""
  3096. _dnssleep=""
  3097. _listraw=""
  3098. _stopRenewOnError=""
  3099. _insecure=""
  3100. _ca_bundle=""
  3101. _nocron=""
  3102. _ecc=""
  3103. _csr=""
  3104. _pre_hook=""
  3105. _post_hook=""
  3106. _renew_hook=""
  3107. _deploy_hook=""
  3108. _logfile=""
  3109. _log=""
  3110. _local_address=""
  3111. _log_level=""
  3112. _auto_upgrade=""
  3113. _listen_v4=""
  3114. _listen_v6=""
  3115. while [ ${#} -gt 0 ] ; do
  3116. case "${1}" in
  3117. --help|-h)
  3118. showhelp
  3119. return
  3120. ;;
  3121. --version|-v)
  3122. version
  3123. return
  3124. ;;
  3125. --install)
  3126. _CMD="install"
  3127. ;;
  3128. --uninstall)
  3129. _CMD="uninstall"
  3130. ;;
  3131. --upgrade)
  3132. _CMD="upgrade"
  3133. ;;
  3134. --issue)
  3135. _CMD="issue"
  3136. ;;
  3137. --deploy)
  3138. _CMD="deploy"
  3139. ;;
  3140. --signcsr)
  3141. _CMD="signcsr"
  3142. ;;
  3143. --showcsr)
  3144. _CMD="showcsr"
  3145. ;;
  3146. --installcert|-i)
  3147. _CMD="installcert"
  3148. ;;
  3149. --renew|-r)
  3150. _CMD="renew"
  3151. ;;
  3152. --renewAll|--renewall)
  3153. _CMD="renewAll"
  3154. ;;
  3155. --revoke)
  3156. _CMD="revoke"
  3157. ;;
  3158. --list)
  3159. _CMD="list"
  3160. ;;
  3161. --installcronjob)
  3162. _CMD="installcronjob"
  3163. ;;
  3164. --uninstallcronjob)
  3165. _CMD="uninstallcronjob"
  3166. ;;
  3167. --cron)
  3168. _CMD="cron"
  3169. ;;
  3170. --toPkcs)
  3171. _CMD="toPkcs"
  3172. ;;
  3173. --createAccountKey|--createaccountkey|-cak)
  3174. _CMD="createAccountKey"
  3175. ;;
  3176. --createDomainKey|--createdomainkey|-cdk)
  3177. _CMD="createDomainKey"
  3178. ;;
  3179. --createCSR|--createcsr|-ccr)
  3180. _CMD="createCSR"
  3181. ;;
  3182. --deactivate)
  3183. _CMD="deactivate"
  3184. ;;
  3185. --updateaccount)
  3186. _CMD="updateaccount"
  3187. ;;
  3188. --registeraccount)
  3189. _CMD="registeraccount"
  3190. ;;
  3191. --domain|-d)
  3192. _dvalue="$2"
  3193. if [ "$_dvalue" ] ; then
  3194. if _startswith "$_dvalue" "-" ; then
  3195. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3196. return 1
  3197. fi
  3198. if [ -z "$_domain" ] ; then
  3199. _domain="$_dvalue"
  3200. else
  3201. if [ "$_altdomains" = "$NO_VALUE" ] ; then
  3202. _altdomains="$_dvalue"
  3203. else
  3204. _altdomains="$_altdomains,$_dvalue"
  3205. fi
  3206. fi
  3207. fi
  3208. shift
  3209. ;;
  3210. --force|-f)
  3211. FORCE="1"
  3212. ;;
  3213. --staging|--test)
  3214. STAGE="1"
  3215. ;;
  3216. --debug)
  3217. if [ -z "$2" ] || _startswith "$2" "-" ; then
  3218. DEBUG="1"
  3219. else
  3220. DEBUG="$2"
  3221. shift
  3222. fi
  3223. ;;
  3224. --webroot|-w)
  3225. wvalue="$2"
  3226. if [ -z "$_webroot" ] ; then
  3227. _webroot="$wvalue"
  3228. else
  3229. _webroot="$_webroot,$wvalue"
  3230. fi
  3231. shift
  3232. ;;
  3233. --standalone)
  3234. wvalue="$NO_VALUE"
  3235. if [ -z "$_webroot" ] ; then
  3236. _webroot="$wvalue"
  3237. else
  3238. _webroot="$_webroot,$wvalue"
  3239. fi
  3240. ;;
  3241. --local-address)
  3242. lvalue="$2"
  3243. _local_address="$_local_address$lvalue,"
  3244. shift
  3245. ;;
  3246. --apache)
  3247. wvalue="apache"
  3248. if [ -z "$_webroot" ] ; then
  3249. _webroot="$wvalue"
  3250. else
  3251. _webroot="$_webroot,$wvalue"
  3252. fi
  3253. ;;
  3254. --tls)
  3255. wvalue="$W_TLS"
  3256. if [ -z "$_webroot" ] ; then
  3257. _webroot="$wvalue"
  3258. else
  3259. _webroot="$_webroot,$wvalue"
  3260. fi
  3261. ;;
  3262. --dns)
  3263. wvalue="dns"
  3264. if ! _startswith "$2" "-" ; then
  3265. wvalue="$2"
  3266. shift
  3267. fi
  3268. if [ -z "$_webroot" ] ; then
  3269. _webroot="$wvalue"
  3270. else
  3271. _webroot="$_webroot,$wvalue"
  3272. fi
  3273. ;;
  3274. --dnssleep)
  3275. _dnssleep="$2"
  3276. Le_DNSSleep="$_dnssleep"
  3277. shift
  3278. ;;
  3279. --keylength|-k)
  3280. _keylength="$2"
  3281. if [ "$_accountkeylength" = "$NO_VALUE" ] ; then
  3282. _accountkeylength="$2"
  3283. fi
  3284. shift
  3285. ;;
  3286. --accountkeylength|-ak)
  3287. _accountkeylength="$2"
  3288. shift
  3289. ;;
  3290. --certpath)
  3291. _certpath="$2"
  3292. shift
  3293. ;;
  3294. --keypath)
  3295. _keypath="$2"
  3296. shift
  3297. ;;
  3298. --capath)
  3299. _capath="$2"
  3300. shift
  3301. ;;
  3302. --fullchainpath)
  3303. _fullchainpath="$2"
  3304. shift
  3305. ;;
  3306. --reloadcmd|--reloadCmd)
  3307. _reloadcmd="$2"
  3308. shift
  3309. ;;
  3310. --password)
  3311. _password="$2"
  3312. shift
  3313. ;;
  3314. --accountconf)
  3315. _accountconf="$2"
  3316. ACCOUNT_CONF_PATH="$_accountconf"
  3317. shift
  3318. ;;
  3319. --home)
  3320. LE_WORKING_DIR="$2"
  3321. shift
  3322. ;;
  3323. --certhome)
  3324. _certhome="$2"
  3325. CERT_HOME="$_certhome"
  3326. shift
  3327. ;;
  3328. --useragent)
  3329. _useragent="$2"
  3330. USER_AGENT="$_useragent"
  3331. shift
  3332. ;;
  3333. --accountemail )
  3334. _accountemail="$2"
  3335. ACCOUNT_EMAIL="$_accountemail"
  3336. shift
  3337. ;;
  3338. --accountkey )
  3339. _accountkey="$2"
  3340. ACCOUNT_KEY_PATH="$_accountkey"
  3341. shift
  3342. ;;
  3343. --days )
  3344. _days="$2"
  3345. Le_RenewalDays="$_days"
  3346. shift
  3347. ;;
  3348. --httpport )
  3349. _httpport="$2"
  3350. Le_HTTPPort="$_httpport"
  3351. shift
  3352. ;;
  3353. --tlsport )
  3354. _tlsport="$2"
  3355. Le_TLSPort="$_tlsport"
  3356. shift
  3357. ;;
  3358. --listraw )
  3359. _listraw="raw"
  3360. ;;
  3361. --stopRenewOnError|--stoprenewonerror|-se )
  3362. _stopRenewOnError="1"
  3363. ;;
  3364. --insecure)
  3365. _insecure="1"
  3366. HTTPS_INSECURE="1"
  3367. ;;
  3368. --ca-bundle)
  3369. _ca_bundle="$(readlink -f $2)"
  3370. CA_BUNDLE="$_ca_bundle"
  3371. shift
  3372. ;;
  3373. --nocron)
  3374. _nocron="1"
  3375. ;;
  3376. --ecc)
  3377. _ecc="isEcc"
  3378. ;;
  3379. --csr)
  3380. _csr="$2"
  3381. shift
  3382. ;;
  3383. --pre-hook)
  3384. _pre_hook="$2"
  3385. shift
  3386. ;;
  3387. --post-hook)
  3388. _post_hook="$2"
  3389. shift
  3390. ;;
  3391. --renew-hook)
  3392. _renew_hook="$2"
  3393. shift
  3394. ;;
  3395. --deploy-hook)
  3396. _deploy_hook="$2"
  3397. shift
  3398. ;;
  3399. --ocsp-must-staple|--ocsp)
  3400. Le_OCSP_Stable="1"
  3401. ;;
  3402. --log|--logfile)
  3403. _log="1"
  3404. _logfile="$2"
  3405. if _startswith "$_logfile" '-' ; then
  3406. _logfile=""
  3407. else
  3408. shift
  3409. fi
  3410. LOG_FILE="$_logfile"
  3411. if [ -z "$LOG_LEVEL" ] ; then
  3412. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3413. fi
  3414. ;;
  3415. --log-level)
  3416. _log_level="$2"
  3417. LOG_LEVEL="$_log_level"
  3418. shift
  3419. ;;
  3420. --auto-upgrade)
  3421. _auto_upgrade="$2"
  3422. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-' ; then
  3423. _auto_upgrade="1"
  3424. else
  3425. shift
  3426. fi
  3427. AUTO_UPGRADE="$_auto_upgrade"
  3428. ;;
  3429. --listen-v4)
  3430. _listen_v4="1"
  3431. Le_Listen_V4="$_listen_v4"
  3432. ;;
  3433. --listen-v6)
  3434. _listen_v6="1"
  3435. Le_Listen_V6="$_listen_v6"
  3436. ;;
  3437. *)
  3438. _err "Unknown parameter : $1"
  3439. return 1
  3440. ;;
  3441. esac
  3442. shift 1
  3443. done
  3444. if [ "${_CMD}" != "install" ] ; then
  3445. __initHome
  3446. if [ "$_log" ] && [ -z "$_logfile" ] ; then
  3447. _logfile="$DEFAULT_LOG_FILE"
  3448. fi
  3449. if [ "$_logfile" ] ; then
  3450. _saveaccountconf "LOG_FILE" "$_logfile"
  3451. fi
  3452. LOG_FILE="$_logfile"
  3453. if [ "$_log_level" ] ; then
  3454. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3455. LOG_LEVEL="$_log_level"
  3456. fi
  3457. _processAccountConf
  3458. fi
  3459. if [ "$DEBUG" ] ; then
  3460. version
  3461. fi
  3462. case "${_CMD}" in
  3463. install) install "$_nocron" ;;
  3464. uninstall) uninstall "$_nocron" ;;
  3465. upgrade) upgrade ;;
  3466. issue)
  3467. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3468. ;;
  3469. deploy)
  3470. deploy "$_domain" "$_deploy_hook" "$_ecc"
  3471. ;;
  3472. signcsr)
  3473. signcsr "$_csr" "$_webroot"
  3474. ;;
  3475. showcsr)
  3476. showcsr "$_csr" "$_domain"
  3477. ;;
  3478. installcert)
  3479. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3480. ;;
  3481. renew)
  3482. renew "$_domain" "$_ecc"
  3483. ;;
  3484. renewAll)
  3485. renewAll "$_stopRenewOnError"
  3486. ;;
  3487. revoke)
  3488. revoke "$_domain" "$_ecc"
  3489. ;;
  3490. deactivate)
  3491. deactivate "$_domain,$_altdomains"
  3492. ;;
  3493. registeraccount)
  3494. registeraccount
  3495. ;;
  3496. updateaccount)
  3497. updateaccount
  3498. ;;
  3499. list)
  3500. list "$_listraw"
  3501. ;;
  3502. installcronjob) installcronjob ;;
  3503. uninstallcronjob) uninstallcronjob ;;
  3504. cron) cron ;;
  3505. toPkcs)
  3506. toPkcs "$_domain" "$_password" "$_ecc"
  3507. ;;
  3508. createAccountKey)
  3509. createAccountKey "$_accountkeylength"
  3510. ;;
  3511. createDomainKey)
  3512. createDomainKey "$_domain" "$_keylength"
  3513. ;;
  3514. createCSR)
  3515. createCSR "$_domain" "$_altdomains" "$_ecc"
  3516. ;;
  3517. *)
  3518. _err "Invalid command: $_CMD"
  3519. showhelp;
  3520. return 1
  3521. ;;
  3522. esac
  3523. _ret="$?"
  3524. if [ "$_ret" != "0" ] ; then
  3525. return $_ret
  3526. fi
  3527. if [ "${_CMD}" = "install" ] ; then
  3528. if [ "$_log" ] ; then
  3529. if [ -z "$LOG_FILE" ] ; then
  3530. LOG_FILE="$DEFAULT_LOG_FILE"
  3531. fi
  3532. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3533. fi
  3534. if [ "$_log_level" ] ; then
  3535. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3536. fi
  3537. _processAccountConf
  3538. fi
  3539. }
  3540. if [ "$INSTALLONLINE" ] ; then
  3541. INSTALLONLINE=""
  3542. _installOnline $BRANCH
  3543. exit
  3544. fi
  3545. main() {
  3546. [ -z "$1" ] && showhelp && return
  3547. if _startswith "$1" '-' ; then _process "$@"; else "$@";fi
  3548. }
  3549. main "$@"